"""
Rutas para gestión de avisos electrónicos
"""

from core.security import get_current_user, validate_access_to_resource
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 api.v1.common.tenant_crud_routes import TenantCRUDRoutes
from .dto import (
    ElectronicNoticeCreateDTO,
    ElectronicNoticeResponseDTO,
    ElectronicNoticeUpdateDTO,
)
from .models import ElectronicNotice
from .service import ElectronicNoticeService

router = TenantCRUDRoutes(
    service=ElectronicNoticeService,
    create_schema=ElectronicNoticeCreateDTO,
    update_schema=ElectronicNoticeUpdateDTO,
    response_schema=ElectronicNoticeResponseDTO,
    prefix="/electronic-notices",
    tags=["electronic-notices"],
    resource_name="Electronic Notice",
    enable_list=True,
    enable_filters=True,
    list_permissions=["cat_notices.view"],
    get_permissions=["cat_notices.view"],
    create_permissions=["cat_notices.create"],
    update_permissions=["cat_notices.edit"],
    delete_permissions=["cat_notices.delete"],
).router


@router.get(
    "/by-pedimento/{pedimento}",
    response_model=List[ElectronicNoticeResponseDTO],
    summary="Get notices by pedimento",
)
async def get_notices_by_pedimento(
    pedimento: str,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """Get all electronic notices for a specific pedimento"""
    tenant_id = validate_access_to_resource(db, company_id, current_user, ["cat_notices.view"])
    notices = ElectronicNoticeService.get_by_pedimento(
        db, pedimento, tenant_id, company_id)
    return [ElectronicNoticeResponseDTO.model_validate(notice) for notice in notices]


@router.get(
    "/by-status/{status}",
    response_model=List[ElectronicNoticeResponseDTO],
    summary="Get notices by status",
)
async def get_notices_by_status(
    status: str,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """Get all electronic notices with a specific status"""
    tenant_id = validate_access_to_resource(db, company_id, current_user, ["cat_notices.view"])
    notices = ElectronicNoticeService.get_by_status(
        db, status, tenant_id, company_id)
    return [ElectronicNoticeResponseDTO.model_validate(notice) for notice in notices]
