import enum
import uuid
from datetime import datetime
from typing import TYPE_CHECKING

from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base

if TYPE_CHECKING:
    from app.models.user import User
    from app.models.department import Department


class PersonnelNumberMode(str, enum.Enum):
    MANUAL = "manual"
    AUTO = "auto"


class Company(Base):
    __tablename__ = "companies"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    slug: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
    plan: Mapped[str] = mapped_column(String(50), default="trial")

    # Mandanten-Status: deaktivierte Firmen können sich nicht mehr einloggen.
    # Von Reseller (eigene Firmen) bzw. SUPER_ADMIN umschaltbar.
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)

    # Reseller-Besitz: Firma wurde von diesem Reseller angelegt und wird von ihm
    # verwaltet (nur Firmen-Ebene, kein Zugriff auf personenbezogene Daten).
    # NULL = direkt von der Plattform (SUPER_ADMIN) verwaltet.
    reseller_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
    )
    logo_url: Mapped[str | None] = mapped_column(Text)
    country: Mapped[str] = mapped_column(String(10), default="DE")
    state: Mapped[str | None] = mapped_column(String(10))
    settings: Mapped[dict] = mapped_column(JSONB, default=dict)

    # Personalnummern-Konfiguration
    personnel_number_required: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    personnel_number_mode: Mapped[str] = mapped_column(String(10), nullable=False, default=PersonnelNumberMode.MANUAL.value)
    personnel_number_next: Mapped[int] = mapped_column(Integer, nullable=False, default=1)

    # Krankmeldungs-Konfiguration: Default-Schwelle für AU-Pflicht (in Tagen).
    # Pro AbsenceType via certificate_after_days überschreibbar.
    sick_note_required_after_days: Mapped[int] = mapped_column(Integer, nullable=False, default=3)

    # Busylight-Pull: SHA-256-Hash des per-Firma-Tokens (Klartext nie in DB).
    busylight_pull_token_hash: Mapped[str | None] = mapped_column(String(64), unique=True)
    busylight_token_created_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))

    # Öffentliches QR-Stempeln: statischer firmenweiter QR-Code → /stamp?t=<token>.
    # Mitarbeiter scannt mit Privat-Handy, meldet sich per Personalnummer + PIN an.
    # Opt-in (default OFF). Token gehasht in DB (SHA-256), Klartext nur beim Rotieren.
    public_stamp_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    public_stamp_token_hash: Mapped[str | None] = mapped_column(String(64), unique=True)
    public_stamp_token_created_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))

    # Kiosk-Konfiguration
    kiosk_require_approval: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    kiosk_track_current_user: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    kiosk_heartbeat_interval_sec: Mapped[int] = mapped_column(Integer, nullable=False, default=30)

    # Mobile-Konfiguration
    mobile_stamping_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)

    # Urlaubsanspruch-Konfiguration
    # Basis-Jahresurlaub (Vollzeit) für neu angelegte Urlaubskonten.
    vacation_default_days: Mapped[int] = mapped_column(Integer, nullable=False, default=30)
    # Anteilige Berechnung im Ein-/Austrittsjahr (Zwölftel-Regel).
    vacation_prorate_first_year: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    # Teilzeit: Anspruch aus Arbeitstagen/Woche des WorkSchedule ableiten (opt-in).
    vacation_from_schedule: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

    # Zwei-Stufen-Genehmigung (agent-12): erst Manager, dann HR/Admin (anderer Genehmiger).
    two_stage_approval_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    # Nur Anträge ab dieser Arbeitstage-Zahl brauchen die zweite Stufe (0 = alle).
    two_stage_min_days: Mapped[int] = mapped_column(Integer, nullable=False, default=0)

    # Freizeitausgleich-Konfiguration
    overtime_overdraft_allowed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    overtime_warning_threshold_hours: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    # Überstunden-Kappung
    overtime_cap_hours: Mapped[int | None] = mapped_column(Integer, nullable=True)
    # Überstunden-Verfall
    overtime_expiry_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    overtime_expiry_month: Mapped[int] = mapped_column(Integer, nullable=False, default=3)   # März
    overtime_expiry_day: Mapped[int] = mapped_column(Integer, nullable=False, default=31)    # 31.
    overtime_max_carryover_hours: Mapped[int | None] = mapped_column(Integer, nullable=True) # None = alles
    # Überstunden-Auszahlung: Selbstbedienung durch Mitarbeiter (Antrag → HR-Genehmigung)
    payout_request_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

    # Relationships
    users: Mapped[list["User"]] = relationship(
        "User", back_populates="company", lazy="noload",
        foreign_keys="User.company_id",
    )
    departments: Mapped[list["Department"]] = relationship("Department", back_populates="company", lazy="noload")

    def __repr__(self) -> str:
        return f"<Company {self.name}>"
