"""
Rutas para gestión de prevalidadores
"""

from typing import List

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user
from api.v1.common.tenant_crud_routes import TenantCRUDRoutes, validate_access_to_resource
from .dto import (
    PrevalidatorCreateDTO,
    PrevalidatorResponseDTO,
    PrevalidatorUpdateDTO,
)
from .models import Prevalidator
from .service import PrevalidatorService

router = APIRouter(prefix="/prevalidators", tags=["prevalidators"])

prevalidator_crud = TenantCRUDRoutes(
    service=PrevalidatorService,
    create_schema=PrevalidatorCreateDTO,
    update_schema=PrevalidatorUpdateDTO,
    response_schema=PrevalidatorResponseDTO,
    prefix="",
    tags=["Prevalidators"],
    resource_name="Prevalidator",
    enable_list=True,
    list_permissions=["cat_prevalidators.view"],
    get_permissions=["cat_prevalidators.view"],
    create_permissions=["cat_prevalidators.create"],
    update_permissions=["cat_prevalidators.edit"],
    delete_permissions=["cat_prevalidators.delete"],
)

# Add custom endpoints


@prevalidator_crud.router.get(
    "/code/{code}",
    response_model=PrevalidatorResponseDTO,
    summary="Get prevalidator by code",
)
async def get_prevalidator_by_code(
    code: str,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """Get a prevalidator by its code"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["cat_prevalidators.view"]
    )
    prevalidator = PrevalidatorService.get_by_code(
        db,
        code,
        tenant_id=tenant_id,
        company_id=company_id,
    )
    if not prevalidator:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Prevalidator not found",
        )
    return PrevalidatorResponseDTO.model_validate(prevalidator)

router.include_router(prevalidator_crud.router)


async def create_prevalidator(
    prevalidator_data: PrevalidatorCreateDTO,
    db: Session = Depends(get_core_db),
):
    """Create a new prevalidator"""
    prevalidator = PrevalidatorService.create(db, prevalidator_data)
    return PrevalidatorResponseDTO.model_validate(prevalidator)


@router.put(
    "/{prevalidator_id}",
    response_model=PrevalidatorResponseDTO,
    summary="Update prevalidator",
)
async def update_prevalidator(
    prevalidator_id: int,
    prevalidator_data: PrevalidatorUpdateDTO,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """Update a prevalidator"""
    validate_access_to_resource(db, company_id, current_user, ["cat_prevalidators.edit"])
    prevalidator = PrevalidatorService.update(
        db, prevalidator_id, prevalidator_data)
    if not prevalidator:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Prevalidator not found",
        )
    return PrevalidatorResponseDTO.model_validate(prevalidator)


@router.delete(
    "/{prevalidator_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="Delete prevalidator",
)
async def delete_prevalidator(
    prevalidator_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """Delete a prevalidator"""
    validate_access_to_resource(db, company_id, current_user, ["cat_prevalidators.delete"])
    success = PrevalidatorService.delete(db, prevalidator_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Prevalidator not found",
        )
    return None


@router.get(
    "/by-customs/{customs}",
    response_model=List[PrevalidatorResponseDTO],
    summary="Get prevalidators by customs",
)
async def get_prevalidators_by_customs(
    customs: str,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """Get all prevalidators for a specific customs"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["cat_prevalidators.view"]
    )
    prevalidators = PrevalidatorService.get_by_customs(db, customs, tenant_id, company_id)
    return [
        PrevalidatorResponseDTO.model_validate(prevalidator)
        for prevalidator in prevalidators
    ]
