from typing import Any, Dict, Optional

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

from .dto import InvoiceTypeDTO
from .models import InvoiceType
from ..rbac import require_ref_view

router = APIRouter(prefix="/invoice-types")


@router.get(
    "/",
    response_model=dict,
    dependencies=[Depends(require_ref_view("ref_invoice_types.view"))],
)
def list_invoice_types(
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=100),
    type: Optional[str] = Query(None, description="Filter by type"),
    operation: Optional[str] = Query(None, description="Filter by operation type (imp, exp, both)"),
    search: str = Query(None, description="Término de búsqueda"),
    db: Session = Depends(get_core_db),
):
    query = db.query(InvoiceType)
    
    if search:
        search_filter = f"%{search}%"
        query = query.filter(
            or_(
                InvoiceType.key.ilike(search_filter),
                InvoiceType.description.ilike(search_filter),
                InvoiceType.note.ilike(search_filter),
                InvoiceType.type.ilike(search_filter),
                InvoiceType.operation.ilike(search_filter)
            )
        )

    # Filter by operation if provided
    if operation:
        query = query.filter(
            (InvoiceType.operation == operation) | (
                InvoiceType.operation == "both")
        )
        
    if type == "imp" and operation == "CR":
        query = query.filter(InvoiceType.operation != "exp")

    total = query.count()
    items = query.offset((page - 1) * page_size).limit(page_size).all()
    return {
        "items": [InvoiceTypeDTO.model_validate(obj) for obj in items],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


@router.get(
    "/{key}",
    response_model=InvoiceTypeDTO,
    dependencies=[Depends(require_ref_view("ref_invoice_types.view"))],
)
def get_invoice_type(
    key: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    obj = db.query(InvoiceType).filter(InvoiceType.key == key).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    return InvoiceTypeDTO.model_validate(obj)


@router.post("/", response_model=InvoiceTypeDTO, status_code=201)
def create_invoice_type(
    data: InvoiceTypeDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = InvoiceType(**data.model_dump())
    db.add(obj)
    db.commit()
    db.refresh(obj)
    return InvoiceTypeDTO.model_validate(obj)


@router.put("/{key}", response_model=InvoiceTypeDTO)
def update_invoice_type(
    key: str,
    data: InvoiceTypeDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(InvoiceType).filter(InvoiceType.key == key).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    for field, value in data.model_dump().items():
        setattr(obj, field, value)
    db.commit()
    db.refresh(obj)
    return InvoiceTypeDTO.model_validate(obj)


@router.delete("/{key}", status_code=204)
def delete_invoice_type(
    key: str,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(has_role("admin")),
):
    obj = db.query(InvoiceType).filter(InvoiceType.key == key).first()
    if not obj:
        raise HTTPException(status_code=404, detail="Not found")
    db.delete(obj)
    db.commit()
    return None
