"""Delivery foundation aggregates — Phase 10.0.

Independent aggregates use UUID references within delivery_db only.
No SQLAlchemy relationship graphs between aggregates.
No dispatch/routing/tracking engines — shells and contracts only.
"""
from __future__ import annotations

import uuid

from sqlalchemy import Index, 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 (
    AuditAction,
    GUID,
    LifecycleStatus,
    ProviderKind,
    ProviderStatus,
    RoutingEngineStatus,
)


class DeliveryOrganization(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Root delivery organization / fleet operator shell for a tenant (Torbat Driver)."""

    __tablename__ = "delivery_organizations"

    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.DRAFT, nullable=False
    )
    legal_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
    timezone: Mapped[str] = mapped_column(String(64), default="Asia/Tehran", nullable=False)
    language: Mapped[str] = mapped_column(String(16), default="fa", nullable=False)
    currency_code: Mapped[str] = mapped_column(String(3), default="IRR", nullable=False)
    settings: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_delivery_organizations_tenant_code"),
        Index("ix_delivery_organizations_tenant_status", "tenant_id", "status"),
        Index("ix_delivery_organizations_tenant_deleted", "tenant_id", "is_deleted"),
    )


class DeliveryHub(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Operational hub / depot under a delivery organization."""

    __tablename__ = "delivery_hubs"

    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)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )
    address: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    timezone: Mapped[str | None] = mapped_column(String(64), nullable=True)
    working_hours: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "organization_id", "code", name="uq_delivery_hubs_tenant_code"
        ),
        Index("ix_delivery_hubs_org", "tenant_id", "organization_id"),
        Index("ix_delivery_hubs_tenant_deleted", "tenant_id", "is_deleted"),
    )


class DeliveryRole(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Local delivery RBAC role catalog shell."""

    __tablename__ = "delivery_roles"

    organization_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_delivery_roles_tenant_code"),
        Index("ix_delivery_roles_tenant_deleted", "tenant_id", "is_deleted"),
    )


class DeliveryPermission(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Local delivery permission catalog shell (complements platform delivery.* tree)."""

    __tablename__ = "delivery_permissions"

    role_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(100), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_delivery_permissions_tenant_code"),
        Index("ix_delivery_permissions_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExternalProviderConfig(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """External fleet/courier/maps provider registration shell — credentials stay here."""

    __tablename__ = "external_provider_configs"

    organization_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    provider_kind: Mapped[ProviderKind] = mapped_column(
        default=ProviderKind.CUSTOM, nullable=False
    )
    adapter_key: Mapped[str] = mapped_column(String(100), nullable=False)
    status: Mapped[ProviderStatus] = mapped_column(
        default=ProviderStatus.REGISTERED, nullable=False
    )
    priority: Mapped[int] = mapped_column(default=100, nullable=False)
    credentials_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)
    config: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    capabilities: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "code", name="uq_external_provider_configs_tenant_code"
        ),
        Index("ix_external_provider_configs_kind", "tenant_id", "provider_kind"),
        Index("ix_external_provider_configs_tenant_deleted", "tenant_id", "is_deleted"),
    )


class RoutingEngineRegistration(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Future routing engine registration — adapter ready, no engine implementation."""

    __tablename__ = "routing_engine_registrations"

    organization_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    adapter_key: Mapped[str] = mapped_column(String(100), nullable=False)
    status: Mapped[RoutingEngineStatus] = mapped_column(
        default=RoutingEngineStatus.REGISTERED, nullable=False
    )
    is_default: Mapped[bool] = mapped_column(default=False, nullable=False)
    config: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    capabilities: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "code", name="uq_routing_engine_registrations_tenant_code"
        ),
        Index("ix_routing_engine_registrations_tenant_deleted", "tenant_id", "is_deleted"),
    )


class DeliveryConfiguration(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Tenant delivery configuration — hours, policies, locale shells."""

    __tablename__ = "delivery_configurations"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    hub_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    working_hours: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    dispatch_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    tracking_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    settlement_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    custom_fields: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    timezone: Mapped[str] = mapped_column(String(64), default="Asia/Tehran", nullable=False)
    language: Mapped[str] = mapped_column(String(16), default="fa", nullable=False)
    currency_code: Mapped[str] = mapped_column(String(3), default="IRR", nullable=False)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "organization_id",
            "code",
            name="uq_delivery_configurations_tenant_code",
        ),
        Index("ix_delivery_configurations_org", "tenant_id", "organization_id"),
        Index("ix_delivery_configurations_tenant_deleted", "tenant_id", "is_deleted"),
    )


class DeliverySetting(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Key/value delivery settings shell."""

    __tablename__ = "delivery_settings"

    organization_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    hub_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    key: Mapped[str] = mapped_column(String(100), nullable=False)
    value: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "organization_id",
            "hub_id",
            "key",
            name="uq_delivery_settings_tenant_key",
        ),
        Index("ix_delivery_settings_tenant_deleted", "tenant_id", "is_deleted"),
    )


class DeliveryAuditLog(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    """Append-only delivery audit trail."""

    __tablename__ = "delivery_audit_logs"

    entity_type: Mapped[str] = mapped_column(String(50), nullable=False)
    entity_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    action: Mapped[AuditAction] = mapped_column(nullable=False)
    actor_user_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
    changes: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    message: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        Index(
            "ix_delivery_audit_entity",
            "tenant_id",
            "entity_type",
            "entity_id",
        ),
    )
