"""Endpoints de los datos fiscales del emisor (una configuración por empresa)."""

from fastapi import APIRouter, Depends, File, Form, Query, UploadFile
from sqlalchemy.orm import Session

from api.v1.modules.core.permissions.dependencies import PermissionChecker
from core.database import get_core_db
from core.security import get_current_user

from . import csd_service, service
from .dto import IssuerSettingsInput, IssuerSettingsResponse

router = APIRouter()


@router.get(
    "/settings/issuer",
    response_model=IssuerSettingsResponse,
    dependencies=[Depends(PermissionChecker(["fin.settings.view"]))],
)
def get_issuer_settings(
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Devuelve 404 mientras la empresa no haya capturado sus datos fiscales."""
    return service.get_issuer_settings(db, current_user["tenant_id"], company_id)


@router.put(
    "/settings/issuer",
    response_model=IssuerSettingsResponse,
    dependencies=[Depends(PermissionChecker(["fin.settings.edit"]))],
)
def save_issuer_settings(
    payload: IssuerSettingsInput,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Alta o actualización (upsert) de los datos fiscales del emisor."""
    return service.save_issuer_settings(
        db,
        payload,
        current_user["tenant_id"],
        company_id,
        current_user.get("sub") or current_user.get("id"),
    )


@router.post(
    "/settings/issuer/csd",
    response_model=IssuerSettingsResponse,
    dependencies=[Depends(PermissionChecker(["fin.settings.edit"]))],
)
async def upload_csd(
    company_id: int = Query(..., description="Company ID"),
    cer: UploadFile = File(..., description="Certificado del CSD (.cer)"),
    key: UploadFile = File(..., description="Llave privada del CSD (.key)"),
    password: str = Form(..., description="Contraseña de la llave privada"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Carga el CSD de la empresa.

    Antes de guardar nada se comprueba que la llave privada corresponde al certificado: si no,
    el error saldría hasta que el PAC rechace un comprobante, con un mensaje que no menciona
    el CSD. La contraseña se guarda cifrada y **no se devuelve nunca**.
    """
    return csd_service.upload_csd(
        db,
        current_user["tenant_id"],
        company_id,
        await cer.read(),
        await key.read(),
        password,
        current_user.get("sub") or current_user.get("id"),
    )


@router.delete(
    "/settings/issuer/csd",
    response_model=IssuerSettingsResponse,
    dependencies=[Depends(PermissionChecker(["fin.settings.edit"]))],
)
def delete_csd(
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Desvincula el CSD y borra sus archivos del almacenamiento."""
    return csd_service.delete_csd(
        db,
        current_user["tenant_id"],
        company_id,
        current_user.get("sub") or current_user.get("id"),
    )
