"""Enrichment vault for archiving enriched data (field-level)."""

from datetime import datetime
from decimal import Decimal
from typing import Optional

from sqlalchemy import (
    BigInteger,
    Text,
    Numeric,
    ForeignKey,
    TIMESTAMP,
    text,
    Index,
    UniqueConstraint,
    Column,
)
from sqlalchemy.orm import mapped_column
from sqlmodel import Field

from ..db import Base


class EnrichmentVault(Base, table=True):
    """
    Field-level archive of enriched data written to Salesforce.

    One row per (usage_id, sfdc_record_id, field_name).
    Stores before/after values for audit trail and data recovery.
    """

    __tablename__ = "enrichment_vault"
    __table_args__ = (
        UniqueConstraint(
            "usage_id",
            "sfdc_record_id",
            "field_name",
            name="uq_vault_usage_record_field",
        ),
        Index("ix_vault_usage", "usage_id"),
        Index("ix_vault_record", "sfdc_record_id", "sfdc_object"),
        Index("ix_vault_account_created", "account_id", "created_at"),
        Index(
            "ix_vault_account_field_valueafter",
            "account_id",
            "field_name",
            "value_after",
        ),
        {"extend_existing": True},
    )

    id: int = Field(
        default=None, sa_column=Column(BigInteger, primary_key=True, autoincrement=True)
    )
    usage_id: int = Field(
        sa_column=mapped_column(
            BigInteger,
            ForeignKey("enrichment_usage.id", ondelete="CASCADE"),
            nullable=False,
        )
    )
    account_id: str = Field(sa_column=mapped_column(Text, nullable=False))

    sfdc_object: str = Field(sa_column=mapped_column(Text, nullable=False))
    sfdc_record_id: str = Field(sa_column=mapped_column(Text, nullable=False))

    field_name: str = Field(sa_column=mapped_column(Text, nullable=False))
    value_before: Optional[str] = Field(
        default=None, sa_column=mapped_column(Text, nullable=True)
    )
    value_after: str = Field(sa_column=mapped_column(Text, nullable=False))
    provider_confidence: Optional[Decimal] = Field(
        default=None, sa_column=mapped_column(Numeric(3, 2), nullable=True)
    )

    created_at: datetime = Field(
        sa_column=mapped_column(
            TIMESTAMP(timezone=True), server_default=text("now()"), nullable=False
        )
    )
