"""Beauty Business foundation aggregates — Phase 14.0.

Independent aggregates use UUID references within beauty_business_db only.
No SQLAlchemy relationship graphs between aggregates.
Booking engine registrations and provider shells only — no engine implementation.
"""
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,
    BookingEngineStatus,
    BusinessFormat,
    GUID,
    LifecycleStatus,
    ProviderKind,
    ProviderStatus,
)


class BeautyOrganization(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Root beauty business organization for a tenant (Torbat Beauty)."""

    __tablename__ = "beauty_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
    )
    business_format: Mapped[BusinessFormat] = mapped_column(
        default=BusinessFormat.SALON, 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_beauty_organizations_tenant_code"),
        Index("ix_beauty_organizations_tenant_status", "tenant_id", "status"),
        Index("ix_beauty_organizations_tenant_deleted", "tenant_id", "is_deleted"),
    )


class BeautyBranch(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Salon / clinic branch under a beauty organization."""

    __tablename__ = "beauty_branches"

    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
    )
    business_format: Mapped[BusinessFormat | None] = mapped_column(nullable=True)
    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_beauty_branches_tenant_code"
        ),
        Index("ix_beauty_branches_org", "tenant_id", "organization_id"),
        Index("ix_beauty_branches_tenant_deleted", "tenant_id", "is_deleted"),
    )


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

    __tablename__ = "beauty_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_beauty_roles_tenant_code"),
        Index("ix_beauty_roles_tenant_deleted", "tenant_id", "is_deleted"),
    )


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

    __tablename__ = "beauty_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_beauty_permissions_tenant_code"),
        Index("ix_beauty_permissions_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ExternalProviderConfig(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """External integration 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 BookingEngineRegistration(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    """Future booking engine registration — adapter ready, no engine implementation."""

    __tablename__ = "booking_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[BookingEngineStatus] = mapped_column(
        default=BookingEngineStatus.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_booking_engine_registrations_tenant_code"
        ),
        Index("ix_booking_engine_registrations_tenant_deleted", "tenant_id", "is_deleted"),
    )


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

    __tablename__ = "beauty_configurations"

    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)
    working_hours: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    booking_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    cancellation_policies: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    reminder_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_beauty_configurations_tenant_code",
        ),
        Index("ix_beauty_configurations_org", "tenant_id", "organization_id"),
        Index("ix_beauty_configurations_tenant_deleted", "tenant_id", "is_deleted"),
    )


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

    __tablename__ = "beauty_settings"

    organization_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    branch_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",
            "branch_id",
            "key",
            name="uq_beauty_settings_tenant_key",
        ),
        Index("ix_beauty_settings_tenant_deleted", "tenant_id", "is_deleted"),
    )


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

    __tablename__ = "beauty_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_beauty_audit_entity",
            "tenant_id",
            "entity_type",
            "entity_id",
        ),
    )
