"""
财务票据域 ORM 模型
映射: fin_invoice_pool / fin_expense_records / fin_expense_details
"""

from __future__ import annotations

import uuid
from datetime import date, datetime

from sqlalchemy import (
    Boolean,
    Date,
    DateTime,
    ForeignKey,
    Numeric,
    String,
    Text,
    func,
)
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import Base


class FinInvoicePool(Base):
    __tablename__ = "fin_invoice_pool"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    uploader_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("sys_users.id"), nullable=True
    )
    file_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    merchant_name: Mapped[str | None] = mapped_column(String(200), nullable=True)
    amount: Mapped[float] = mapped_column(Numeric(14, 2), default=0)
    invoice_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    type: Mapped[str] = mapped_column(String(30), nullable=False, default="expense")
    ai_extracted_data: Mapped[dict] = mapped_column(JSONB, default=dict)
    is_used: Mapped[bool] = mapped_column(Boolean, default=False)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now()
    )
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)

    uploader: Mapped["SysUser | None"] = relationship("SysUser", lazy="selectin")  # noqa: F821


class FinExpenseRecord(Base):
    __tablename__ = "fin_expense_records"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    system_no: Mapped[str] = mapped_column(String(30), unique=True, nullable=False)
    applicant_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("sys_users.id"), nullable=False
    )
    total_amount: Mapped[float] = mapped_column(Numeric(14, 2), default=0)
    status: Mapped[str] = mapped_column(String(20), nullable=False, default="draft")
    remark: Mapped[str | None] = mapped_column(Text, nullable=True)
    approved_by: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("sys_users.id"), nullable=True
    )
    approved_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now()
    )
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)

    applicant: Mapped["SysUser"] = relationship(  # noqa: F821
        "SysUser", foreign_keys=[applicant_id], lazy="selectin"
    )
    approver: Mapped["SysUser | None"] = relationship(  # noqa: F821
        "SysUser", foreign_keys=[approved_by], lazy="selectin"
    )
    details: Mapped[list[FinExpenseDetail]] = relationship(
        "FinExpenseDetail", back_populates="expense_record", lazy="selectin"
    )


class FinExpenseDetail(Base):
    __tablename__ = "fin_expense_details"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    expense_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("fin_expense_records.id"), nullable=False
    )
    invoice_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("fin_invoice_pool.id"), nullable=True
    )
    expense_desc: Mapped[str | None] = mapped_column(String(500), nullable=True)
    expense_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    original_type: Mapped[str | None] = mapped_column(String(50), nullable=True)
    offset_type: Mapped[str | None] = mapped_column(String(50), nullable=True)
    amount: Mapped[float] = mapped_column(Numeric(14, 2), default=0)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now()
    )
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)

    expense_record: Mapped[FinExpenseRecord] = relationship(
        "FinExpenseRecord", back_populates="details"
    )
    invoice: Mapped[FinInvoicePool | None] = relationship(
        "FinInvoicePool", lazy="selectin"
    )


class FinSalesInvoice(Base):
    """销项发票表（AR 应收账款核心）"""
    __tablename__ = "finance_sales_invoices"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    issuer: Mapped[str] = mapped_column(String(200), nullable=False)
    receiver_customer_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("crm_customers.id"), nullable=False
    )
    invoice_number: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
    amount: Mapped[float] = mapped_column(Numeric(14, 2), default=0)
    billing_date: Mapped[date] = mapped_column(Date, nullable=False)
    payment_status: Mapped[str] = mapped_column(
        String(20), nullable=False, default="未回款"
    )
    payment_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    payment_amount: Mapped[float] = mapped_column(Numeric(14, 2), default=0)
    remark: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_by: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("sys_users.id"), nullable=True
    )
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now()
    )
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False)

    # Relationships
    receiver_customer: Mapped["CrmCustomer"] = relationship(  # noqa: F821
        "CrmCustomer", lazy="selectin"
    )
    creator: Mapped["SysUser | None"] = relationship(  # noqa: F821
        "SysUser", lazy="selectin"
    )
