from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user

from . import service, taxes_service
from .dto import (
    InvoiceClientReviewInput,
    InvoiceCreate,
    InvoiceItemCreate,
    InvoiceItemResponse,
    InvoiceItemTaxInput,
    InvoiceItemTaxResponse,
    InvoiceItemUpdate,
    InvoiceResponse,
    InvoiceUpdate,
    PaymentCreate,
    PaymentResponse,
)

router = APIRouter()


def _uid(cu: dict) -> str | None:
    return cu.get("sub") or cu.get("id")


@router.get("/invoices", response_model=list[InvoiceResponse])
def list_invoices(
    company_id: int = Query(...),
    search: str | None = Query(None),
    inv_status: str | None = Query(None, alias="status"),
    account_id: int | None = Query(None),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return service.get_invoices(db, current_user["tenant_id"], company_id, search, inv_status, account_id)


@router.get("/invoices/{invoice_id}", response_model=InvoiceResponse)
def get_invoice(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.get_invoice(db, invoice_id, current_user["tenant_id"], company_id)


@router.post("/invoices", response_model=InvoiceResponse, status_code=status.HTTP_201_CREATED)
def create_invoice(payload: InvoiceCreate, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.create_invoice(db, payload, current_user["tenant_id"], company_id, _uid(current_user))


@router.post("/invoices/from-shipment", response_model=InvoiceResponse, status_code=status.HTTP_201_CREATED)
def generate_from_shipment(shipment_id: int = Query(...), company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.generate_from_shipment(db, shipment_id, current_user["tenant_id"], company_id, _uid(current_user))


@router.patch("/invoices/{invoice_id}", response_model=InvoiceResponse)
def update_invoice(invoice_id: int, payload: InvoiceUpdate, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.update_invoice(db, invoice_id, payload, current_user["tenant_id"], company_id, _uid(current_user))


@router.patch("/invoices/{invoice_id}/emit", response_model=InvoiceResponse)
def emit_invoice(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.emit_invoice(db, invoice_id, current_user["tenant_id"], company_id)


@router.patch("/invoices/{invoice_id}/send", response_model=InvoiceResponse)
def send_invoice(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    """Genera el PDF, lo guarda en MinIO y marca la factura como enviada (R-F-05)."""
    return service.send_invoice(db, invoice_id, current_user["tenant_id"], company_id, _uid(current_user))


@router.get("/invoices/{invoice_id}/pdf-url")
def get_invoice_pdf_url(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    """URL firmada fresca del PDF de la factura (R-F-05)."""
    return {"url": service.get_invoice_pdf_url(db, invoice_id, current_user["tenant_id"], company_id)}


@router.patch("/invoices/{invoice_id}/client-review", response_model=InvoiceResponse)
def mark_client_review(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    """Marca la factura en revisión del cliente (R-F-06)."""
    return service.mark_client_review(db, invoice_id, current_user["tenant_id"], company_id, _uid(current_user))


@router.patch("/invoices/{invoice_id}/client-decision", response_model=InvoiceResponse)
def client_review_decision(invoice_id: int, payload: InvoiceClientReviewInput, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    """Registra la decisión del cliente sobre la factura: aprobada o con observaciones (R-F-06)."""
    return service.client_review_decision(db, invoice_id, payload, current_user["tenant_id"], company_id, _uid(current_user))


@router.patch("/invoices/{invoice_id}/cancel", response_model=InvoiceResponse)
def cancel_invoice(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.cancel_invoice(db, invoice_id, current_user["tenant_id"], company_id)


@router.delete("/invoices/{invoice_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_invoice(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    service.delete_invoice(db, invoice_id, current_user["tenant_id"], company_id)


# ----- Conceptos -----

@router.get("/invoices/{invoice_id}/items", response_model=list[InvoiceItemResponse])
def list_items(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.get_items(db, invoice_id, current_user["tenant_id"], company_id)


@router.post("/invoice-items", response_model=InvoiceItemResponse, status_code=status.HTTP_201_CREATED)
def create_item(payload: InvoiceItemCreate, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.create_item(db, payload, current_user["tenant_id"], company_id)


@router.patch("/invoice-items/{item_id}", response_model=InvoiceItemResponse)
def update_item(item_id: int, payload: InvoiceItemUpdate, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.update_item(db, item_id, payload, current_user["tenant_id"], company_id)


@router.delete("/invoice-items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    service.delete_item(db, item_id, current_user["tenant_id"], company_id)


# ----- Pagos (cobranza) -----

@router.get("/invoices/{invoice_id}/payments", response_model=list[PaymentResponse])
def list_payments(invoice_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.get_payments(db, invoice_id, current_user["tenant_id"], company_id)


@router.post("/payments", response_model=PaymentResponse, status_code=status.HTTP_201_CREATED)
def create_payment(payload: PaymentCreate, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return service.create_payment(db, payload, current_user["tenant_id"], company_id)


@router.delete("/payments/{payment_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_payment(payment_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    service.delete_payment(db, payment_id, current_user["tenant_id"], company_id)


# ----- Impuestos por partida -----
# El traslado de IVA se deriva del % de la factura; estos endpoints son para ajustarlo
# (retenciones, tasas distintas) cuando el caso lo pide.

@router.get("/invoice-items/{item_id}/taxes", response_model=list[InvoiceItemTaxResponse])
def list_item_taxes(item_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    return taxes_service.list_item_taxes(db, item_id, current_user["tenant_id"], company_id)


@router.put("/invoice-items/{item_id}/taxes", response_model=InvoiceItemTaxResponse)
def set_item_tax(item_id: int, payload: InvoiceItemTaxInput, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    """Alta o ajuste. La combinación impuesto + traslado/retención es única por partida."""
    return taxes_service.set_item_tax(
        db, item_id, payload.tax_id, payload.rate, payload.is_withholding,
        current_user["tenant_id"], company_id,
    )


@router.delete("/invoice-item-taxes/{tax_row_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item_tax(tax_row_id: int, company_id: int = Query(...), current_user: dict = Depends(get_current_user), db: Session = Depends(get_core_db)):
    taxes_service.delete_item_tax(db, tax_row_id, current_user["tenant_id"], company_id)
