"""Staff and commission aggregates — Phase 14.6."""
from __future__ import annotations

import uuid
from datetime import date, datetime

from sqlalchemy import Boolean, Date, DateTime, Index, Numeric, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.core.database import Base
from app.models.base import (
    ActorAuditMixin,
    SoftDeleteMixin,
    TenantMixin,
    TimestampMixin,
    UUIDPrimaryKeyMixin,
)
from app.models.types import CommissionStatus, GUID, LifecycleStatus, StaffKind


class StaffProfile(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "staff_profiles"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    display_name: Mapped[str] = mapped_column(String(255), nullable=False)
    kind: Mapped[StaffKind] = mapped_column(default=StaffKind.OTHER, nullable=False)
    external_user_ref: Mapped[str | None] = mapped_column(String(100), nullable=True)
    mobile: Mapped[str | None] = mapped_column(String(32), nullable=True)
    email: Mapped[str | None] = mapped_column(String(255), nullable=True)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )
    hire_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_staff_profiles_tenant_code"),
        Index("ix_staff_profiles_org", "tenant_id", "organization_id"),
        Index("ix_staff_profiles_branch", "tenant_id", "branch_id"),
    )


class StaffSkill(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "staff_skills"

    staff_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    skill_code: Mapped[str] = mapped_column(String(50), nullable=False)
    skill_name: Mapped[str] = mapped_column(String(255), nullable=False)
    level: Mapped[int] = mapped_column(default=1, nullable=False)
    is_certified: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "staff_id", "skill_code", name="uq_staff_skills_code"
        ),
        Index("ix_staff_skills_staff", "tenant_id", "staff_id"),
    )


class StaffCertificate(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "staff_certificates"

    staff_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    title: Mapped[str] = mapped_column(String(255), nullable=False)
    issuer: Mapped[str | None] = mapped_column(String(255), nullable=True)
    issued_at: Mapped[date | None] = mapped_column(Date, nullable=True)
    expires_at: Mapped[date | None] = mapped_column(Date, nullable=True)
    document_file_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)

    __table_args__ = (
        Index("ix_staff_certificates_staff", "tenant_id", "staff_id"),
    )


class CommissionRule(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "commission_rules"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    rule_type: Mapped[str] = mapped_column(String(50), nullable=False)
    rate_percent: Mapped[float | None] = mapped_column(Numeric(8, 4), nullable=True)
    flat_amount: Mapped[float | None] = mapped_column(Numeric(18, 2), nullable=True)
    applies_to_service_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )
    config: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_commission_rules_tenant_code"),
        Index("ix_commission_rules_org", "tenant_id", "organization_id"),
    )


class CommissionEntry(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "commission_entries"

    staff_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    commission_rule_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=False)
    appointment_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    amount: Mapped[float] = mapped_column(Numeric(18, 2), nullable=False)
    status: Mapped[CommissionStatus] = mapped_column(
        default=CommissionStatus.PENDING, nullable=False
    )
    accrued_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        Index("ix_commission_entries_staff", "tenant_id", "staff_id"),
        Index("ix_commission_entries_status", "tenant_id", "status"),
    )
