"""
Routes for PedimentoPayments 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_payments import (
    PedimentoPaymentsCreate,
    PedimentoPaymentsResponse,
    PedimentoPaymentsUpdate,
)
from ..services.pedimento_payments import PedimentoPaymentsService

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


@router.get("/", response_model=List[PedimentoPaymentsResponse])
async def list_payments(
    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 payments for a pedimento"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.view"]
    )

    payments = PedimentoPaymentsService.get_by_pedimento_id(
        db, pedimento_id, tenant_id, company_id
    )
    return payments


@router.get("/{id}", response_model=PedimentoPaymentsResponse)
async def get_payment(
    pedimento_id: int,
    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 payment by ID"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.view"]
    )

    payment = PedimentoPaymentsService.get_by_id(
        db, id, pedimento_id, tenant_id, company_id
    )
    if not payment:
        raise HTTPException(status_code=404, detail="Payment not found")

    return payment


@router.post("/", response_model=PedimentoPaymentsResponse, status_code=201)
async def create_payment(
    pedimento_id: int,
    data: PedimentoPaymentsCreate,
    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 payment"""
    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")

    payment = PedimentoPaymentsService.create(db, data, tenant_id, company_id)
    return payment


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

    payment = PedimentoPaymentsService.update(
        db, id, pedimento_id, tenant_id, company_id, data
    )
    if not payment:
        raise HTTPException(status_code=404, detail="Payment not found")

    return payment


@router.delete("/{id}", status_code=204)
async def delete_payment(
    pedimento_id: int,
    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 payment"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.edit"]
    )

    success = PedimentoPaymentsService.delete(
        db, id, pedimento_id, tenant_id, company_id
    )
    if not success:
        raise HTTPException(status_code=404, detail="Payment not found")

    return None
