"""
Rutas para gestión de relaciones entre partes y países - Anexo 24
"""

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 .dto import (
    PartCountryCreateDTO,
    PartCountryResponseDTO,
    PartCountryUpdateDTO,
    PartCountriesBulkResponseDTO,
)
from .models import PartCountry
from .service import PartCountryService

router = APIRouter(prefix="/part-countries", tags=["part-countries"])


@router.get(
    "",
    response_model=dict,
    summary="Get all part-country relationships",
)
async def get_all_part_countries(
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=100),
    part_id: int = Query(None),
    country_code: str = Query(None),
    preference: str = Query(None),
    db: Session = Depends(get_core_db),
):
    """Get all part-country relationships with optional filtering and pagination"""
    filters = {}
    if part_id:
        filters["part_id"] = part_id
    if country_code:
        filters["country_code"] = country_code
    if preference:
        filters["preference"] = preference

    part_countries, total = PartCountryService.get_all(db, skip, limit, filters)

    return {
        "data": [PartCountryResponseDTO.model_validate(pc) for pc in part_countries],
        "total": total,
        "skip": skip,
        "limit": limit,
    }


@router.get(
    "/{part_country_id}",
    response_model=PartCountryResponseDTO,
    summary="Get part-country relationship by ID",
)
async def get_part_country(
    part_country_id: int,
    db: Session = Depends(get_core_db),
):
    """Get a part-country relationship by its ID"""
    part_country = PartCountryService.get_by_id(db, part_country_id)
    if not part_country:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Part-country relationship not found",
        )
    return PartCountryResponseDTO.model_validate(part_country)


@router.get(
    "/part/{part_id}",
    response_model=dict,
    summary="Get all countries for a part",
)
async def get_part_countries(
    part_id: int,
    db: Session = Depends(get_core_db),
):
    """Get all countries associated with a specific part"""
    part_countries = PartCountryService.get_by_part_id(db, part_id)
    
    return {
        "data": [PartCountryResponseDTO.model_validate(pc) for pc in part_countries],
        "total": len(part_countries),
    }


@router.post(
    "",
    response_model=PartCountryResponseDTO,
    status_code=status.HTTP_201_CREATED,
    summary="Create part-country relationship",
)
async def create_part_country(
    part_country_data: PartCountryCreateDTO,
    db: Session = Depends(get_core_db),
):
    """Create a new part-country relationship"""
    part_country = PartCountryService.create(db, part_country_data)
    return PartCountryResponseDTO.model_validate(part_country)


@router.post(
    "/part/{part_id}/bulk",
    response_model=dict,
    status_code=status.HTTP_201_CREATED,
    summary="Bulk create/update part-country relationships",
)
async def bulk_create_part_countries(
    part_id: int,
    countries_data: List[PartCountryCreateDTO],
    db: Session = Depends(get_core_db),
):
    """Create or replace all part-country relationships for a part"""
    part_countries = PartCountryService.bulk_create(db, part_id, countries_data)
    
    return {
        "data": [PartCountryResponseDTO.model_validate(pc) for pc in part_countries],
        "total": len(part_countries),
    }


@router.put(
    "/{part_country_id}",
    response_model=PartCountryResponseDTO,
    summary="Update part-country relationship",
)
async def update_part_country(
    part_country_id: int,
    part_country_data: PartCountryUpdateDTO,
    db: Session = Depends(get_core_db),
):
    """Update a part-country relationship"""
    part_country = PartCountryService.update(db, part_country_id, part_country_data)
    if not part_country:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Part-country relationship not found",
        )
    return PartCountryResponseDTO.model_validate(part_country)


@router.delete(
    "/{part_country_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="Delete part-country relationship",
)
async def delete_part_country(
    part_country_id: int,
    db: Session = Depends(get_core_db),
):
    """Delete a part-country relationship"""
    success = PartCountryService.delete(db, part_country_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Part-country relationship not found",
        )
