"""Settlement aggregates — Phase 10.8.

Uses AccountingProvider protocol refs only — NO journal entries in delivery_db.
"""
from __future__ import annotations

import uuid
from decimal import Decimal

from sqlalchemy import 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,
    OptimisticLockMixin,
    SoftDeleteMixin,
    TenantMixin,
    TimestampMixin,
    UUIDPrimaryKeyMixin,
)
from app.models.types import GUID, SettlementIntentStatus, SettlementLineKind


class SettlementIntent(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "settlement_intents"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    status: Mapped[SettlementIntentStatus] = mapped_column(
        default=SettlementIntentStatus.DRAFT, nullable=False
    )
    driver_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    dispatch_job_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    external_settlement_ref: Mapped[str | None] = mapped_column(
        String(255), nullable=True
    )
    total_amount: Mapped[Decimal] = mapped_column(Numeric(18, 4), nullable=False)
    currency_code: Mapped[str] = mapped_column(String(3), nullable=False, default="IRR")
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_settlement_intents_tenant_code"),
        Index("ix_settlement_intents_tenant_status", "tenant_id", "status"),
        Index("ix_settlement_intents_tenant_deleted", "tenant_id", "is_deleted"),
    )


class SettlementLine(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "settlement_lines"

    settlement_intent_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    kind: Mapped[SettlementLineKind] = mapped_column(nullable=False)
    description: Mapped[str | None] = mapped_column(String(255), nullable=True)
    amount: Mapped[Decimal] = mapped_column(Numeric(18, 4), nullable=False)
    currency_code: Mapped[str] = mapped_column(String(3), nullable=False, default="IRR")
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        Index("ix_settlement_lines_intent", "tenant_id", "settlement_intent_id"),
    )
