"""
Caché del PDF de reporte DODA (S3 + columnas en a76.doda) e invalidación.
"""

from __future__ import annotations

import logging
from typing import Optional

from sqlalchemy.orm import Session

from core.config import settings
from core.s3_keys import doda_report_pdf_key
from core import storage_s3

from .models import Doda

logger = logging.getLogger(__name__)


def _delete_stored_s3_key(key: Optional[str]) -> None:
    if not key or not settings.use_s3_object_storage:
        return
    storage_s3.delete_object_if_exists(key)


def clear_doda_report_fields(doda: Doda) -> None:
    doda.doda_report_pdf_path = None
    doda.doda_report_pdf_generated_at = None
    doda.doda_report_source_fingerprint = None


def touch_invalidate_doda_report(
    db: Session,
    *,
    tenant_id: int,
    company_id: int,
    doda_id: int,
    doda: Optional[Doda] = None,
) -> None:
    """
    Borra el PDF previo en S3 (si aplica) y limpia columnas de caché en el DODA.
    Llamar tras mutaciones de DODA o de tablas hijas.
    """
    if doda is None:
        doda = (
            db.query(Doda)
            .filter(
                Doda.id == doda_id,
                Doda.tenant_id == tenant_id,
                Doda.company_id == company_id,
            )
            .first()
        )
    if not doda:
        return

    keys: set[str] = set()
    if doda.doda_report_pdf_path:
        keys.add(doda.doda_report_pdf_path)
    try:
        keys.add(doda_report_pdf_key(tenant_id, company_id, doda_id))
    except ValueError:
        pass

    for k in keys:
        _delete_stored_s3_key(k)

    clear_doda_report_fields(doda)
    try:
        db.add(doda)
        db.commit()
    except Exception:
        db.rollback()
        logger.exception("Error invalidating DODA report cache doda_id=%s", doda_id)
