from typing import Optional
from sqlalchemy import Integer, ForeignKey, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from core.database import Base
from api.v1.common.base_models import BaseTimestampMixin

class AppSetting(Base, BaseTimestampMixin):
    """
    Unified configuration table for Anexo 76.
    Replaces 14 legacy tables using a hierarchical JSONB override system.
    """
    __tablename__ = "app_settings"
    __table_args__ = (
        UniqueConstraint("tenant_id", "company_id", name="uq_app_settings_tenant_company"),
        {"schema": "a76"},
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    
    # Hierarchy levels (Nullable to allow Global/Tenant/Company scoping)
    tenant_id: Mapped[Optional[int]] = mapped_column(
        Integer, ForeignKey("core.tenants.id"), nullable=True, index=True
    )
    company_id: Mapped[Optional[int]] = mapped_column(
        Integer, ForeignKey("a76.company.id"), nullable=True, index=True
    )
    
    # The actual configuration payload
    settings: Mapped[dict] = mapped_column(JSONB, nullable=False, default={})

    def __repr__(self):
        return f"<AppSetting(id={self.id}, tenant={self.tenant_id}, company={self.company_id})>"
