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

from fastapi import APIRouter, Depends, Query
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 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"),
    )
