"""
Rutas para gestión de firmas
"""

from typing import Any, Dict

from api.v1.common.tenant_crud_routes import TenantCRUDRoutes, validate_access_to_resource
from fastapi import Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from core.database import get_core_db

from .dto import SignatureCreateDTO, SignatureResponseDTO, SignatureUpdateDTO
from .service import SignatureService

# Create router using TenantCRUDRoutes factory
signature_crud = TenantCRUDRoutes(
    service=SignatureService,
    create_schema=SignatureCreateDTO,
    update_schema=SignatureUpdateDTO,
    response_schema=SignatureResponseDTO,
    prefix="/signatures",
    tags=["signatures"],
    resource_name="Signature",
    id_name="id",  # Using numeric ID
    enable_list=True,  # Enable GET /signatures with pagination
    enable_filters=True,  # Enable filtering by code
    default_page_size=50,
    max_page_size=100,
    list_permissions=["cat_signatures.view"],
    get_permissions=["cat_signatures.view"],
    create_permissions=["cat_signatures.create"],
    update_permissions=["cat_signatures.edit"],
    delete_permissions=["cat_signatures.delete"],
)

router = signature_crud.router


@router.get(
    "/code/{code}",
    response_model=SignatureResponseDTO,
    summary="Get signature by code",
)
async def get_signature_by_code(
    code: str,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(signature_crud.db_dependency),
    current_user: Dict[str, Any] = Depends(signature_crud.auth_dependency),
):
    """Get a signature by its code"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["cat_signatures.view"]
    )
    signature = SignatureService.get_by_code(db, code, tenant_id, company_id)
    if not signature:
        raise HTTPException(
            status_code=404,
            detail="Signature not found",
        )
    return SignatureResponseDTO.model_validate(signature)


@router.delete(
    "/{signature_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="Delete signature",
)
async def delete_signature(
    signature_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(signature_crud.auth_dependency),
):
    """Delete a signature"""
    validate_access_to_resource(db, company_id, current_user, ["cat_signatures.delete"])
    success = SignatureService.delete(db, signature_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Signature not found",
        )
    return None
