"""
Routes for PedimentoDecrementables CRUD operations
"""

from typing import Any, Dict, List

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from ..dtos.pedimento_decrementables import (
    PedimentoDecrementablesCreate,
    PedimentoDecrementablesResponse,
    PedimentoDecrementablesUpdate,
)
from ..services.pedimento_decrementables import PedimentoDecrementablesService

router = APIRouter(prefix="/{pedimento_id}/decrementables")


@router.get("/", response_model=List[PedimentoDecrementablesResponse])
async def list_decrementables(
    pedimento_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Get all decrementables for a pedimento"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.view"]
    )

    decrementables = PedimentoDecrementablesService.get_by_pedimento_id(
        db, pedimento_id, tenant_id, company_id
    )
    return decrementables


@router.get("/{decrementable_id}", response_model=PedimentoDecrementablesResponse)
async def get_decrementable(
    pedimento_id: int,
    decrementable_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Get a specific decrementable by ID"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.view"]
    )

    decrementable = PedimentoDecrementablesService.get_by_id(
        db, decrementable_id, pedimento_id, tenant_id, company_id
    )
    if not decrementable:
        raise HTTPException(status_code=404, detail="Decrementable not found")

    return decrementable


@router.post("/", response_model=PedimentoDecrementablesResponse, status_code=201)
async def create_decrementable(
    pedimento_id: int,
    data: PedimentoDecrementablesCreate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Create a new decrementable"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.edit"]
    )

    # Ensure pedimento_id matches
    if data.pedimento_id != pedimento_id:
        raise HTTPException(status_code=400, detail="Pedimento ID mismatch")

    decrementable = PedimentoDecrementablesService.create(
        db, data, tenant_id, company_id
    )
    return decrementable


@router.put("/{decrementable_id}", response_model=PedimentoDecrementablesResponse)
async def update_decrementable(
    pedimento_id: int,
    decrementable_id: int,
    data: PedimentoDecrementablesUpdate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Update a decrementable"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.edit"]
    )

    decrementable = PedimentoDecrementablesService.update(
        db, decrementable_id, pedimento_id, tenant_id, company_id, data
    )
    if not decrementable:
        raise HTTPException(status_code=404, detail="Decrementable not found")

    return decrementable


@router.delete("/{decrementable_id}", status_code=204)
async def delete_decrementable(
    pedimento_id: int,
    decrementable_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Delete a decrementable"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.edit"]
    )

    success = PedimentoDecrementablesService.delete(
        db, decrementable_id, pedimento_id, tenant_id, company_id
    )
    if not success:
        raise HTTPException(status_code=404, detail="Decrementable not found")

    return None
