from __future__ import annotations

import uuid
from datetime import date, datetime

from sqlalchemy import (
    Boolean,
    Column,
    Date,
    DateTime,
    ForeignKey,
    ForeignKeyConstraint,
    Index,
    Integer,
    String,
    Table,
    UniqueConstraint,
    func,
)
from sqlalchemy.orm import Mapped, foreign, mapped_column, relationship, remote

from app.db.base_class import Base

employee_role_links = Table(
    "employee_role_links",
    Base.metadata,
    Column("employee_id", String(36), ForeignKey("employees.id"), primary_key=True),
    Column("role_id", String(36), ForeignKey("roles.id"), primary_key=True),
)


class Employee(Base):
    __tablename__ = "employees"
    __table_args__ = (
        UniqueConstraint("tenant_id", "id", name="uq_employees_tenant_id"),
        UniqueConstraint(
            "tenant_id",
            "employee_no",
            name="uq_employees_tenant_employee_no",
        ),
        UniqueConstraint(
            "tenant_id",
            "email",
            name="uq_employees_tenant_email",
        ),
        ForeignKeyConstraint(
            ["tenant_id", "organization_unit_id"],
            ["organization_units.tenant_id", "organization_units.id"],
            name="fk_employees_tenant_organization_unit",
            ondelete="RESTRICT",
        ),
        ForeignKeyConstraint(
            ["tenant_id", "manager_id"],
            ["employees.tenant_id", "employees.id"],
            name="fk_employees_tenant_manager",
            ondelete="RESTRICT",
        ),
        Index("ix_employees_tenant_status", "tenant_id", "employment_status"),
        Index("ix_employees_tenant_name", "tenant_id", "name"),
    )

    id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    tenant_id: Mapped[str] = mapped_column(
        ForeignKey("tenants.tenant_id", ondelete="RESTRICT"),
        nullable=False,
        server_default="default",
    )
    employee_no: Mapped[str] = mapped_column(String(50), index=True)
    name: Mapped[str] = mapped_column(String(100), index=True)
    email: Mapped[str] = mapped_column(String(255), index=True)
    gender: Mapped[str | None] = mapped_column(String(20), nullable=True)
    birth_date: Mapped[date | None] = mapped_column(Date(), nullable=True)
    phone: Mapped[str | None] = mapped_column(String(30), nullable=True)
    join_date: Mapped[date | None] = mapped_column(Date(), nullable=True)
    location: Mapped[str | None] = mapped_column(String(100), nullable=True)
    position: Mapped[str] = mapped_column(String(100), default="员工")
    grade: Mapped[str] = mapped_column(String(20), default="P3", index=True)
    cost_center: Mapped[str | None] = mapped_column(String(50), nullable=True)
    finance_owner_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    bank_name: Mapped[str | None] = mapped_column(String(120), nullable=True)
    bank_account_no: Mapped[str | None] = mapped_column(String(80), nullable=True)
    bank_account_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
    employment_status: Mapped[str] = mapped_column(String(30), default="在职", index=True)
    sync_state: Mapped[str] = mapped_column(String(30), default="已同步")
    compliance_score: Mapped[int] = mapped_column(Integer, default=100)
    spotlight: Mapped[bool] = mapped_column(Boolean, default=False)
    last_sync_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    organization_unit_id: Mapped[str | None] = mapped_column(nullable=True, index=True)
    manager_id: Mapped[str | None] = mapped_column(nullable=True, index=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )

    organization_unit = relationship(
        "OrganizationUnit",
        back_populates="employees",
        primaryjoin=(
            "and_(Employee.tenant_id == OrganizationUnit.tenant_id, "
            "foreign(Employee.organization_unit_id) == OrganizationUnit.id)"
        ),
        foreign_keys=[organization_unit_id],
        overlaps="manager,reports",
    )
    manager = relationship(
        "Employee",
        primaryjoin=lambda: (
            (Employee.tenant_id == remote(Employee.tenant_id))
            & (foreign(Employee.manager_id) == remote(Employee.id))
        ),
        remote_side=[tenant_id, id],
        foreign_keys=[manager_id],
        back_populates="reports",
        overlaps="organization_unit",
    )
    reports = relationship(
        "Employee",
        primaryjoin=lambda: (
            (Employee.tenant_id == remote(Employee.tenant_id))
            & (Employee.id == foreign(remote(Employee.manager_id)))
        ),
        foreign_keys=[manager_id],
        back_populates="manager",
        overlaps="organization_unit",
    )
    roles = relationship("Role", secondary=employee_role_links, back_populates="employees")
    tenant_memberships = relationship(
        "TenantMembership",
        back_populates="employee",
        cascade="all, delete-orphan",
        overlaps="memberships,tenant",
    )
    change_logs = relationship(
        "EmployeeChangeLog",
        back_populates="employee",
        cascade="all, delete-orphan",
        order_by="desc(EmployeeChangeLog.occurred_at)",
    )
    reimbursement_requests = relationship("ReimbursementRequest", back_populates="employee")
