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
from .dto import DocumentCreate, DocumentResponse, DocumentUpdate

router = APIRouter()


@router.get("/documents", response_model=list[DocumentResponse])
def list_documents(
    company_id: int = Query(..., description="Company ID"),
    account_id: int | None = Query(None, description="Filtrar por cliente"),
    supplier_id: int | None = Query(None, description="Filtrar por proveedor"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    return service.get_documents(db, tenant_id, company_id, account_id, supplier_id)


@router.post("/documents", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED)
def create_document(
    payload: DocumentCreate,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    user_id = current_user.get("sub") or current_user.get("id")
    return service.create_document(db, payload, tenant_id, company_id, user_id)


@router.patch("/documents/{document_id}", response_model=DocumentResponse)
def update_document(
    document_id: int,
    payload: DocumentUpdate,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    return service.update_document(db, document_id, payload, tenant_id, company_id)


@router.delete("/documents/{document_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_document(
    document_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    service.delete_document(db, document_id, tenant_id, company_id)
