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 SupplierCreate, SupplierResponse, SupplierUpdate

router = APIRouter()


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


@router.get("/suppliers", response_model=list[SupplierResponse])
def list_suppliers(
    company_id: int = Query(..., description="Company ID"),
    search: str | None = Query(None, description="Búsqueda por nombre o RFC"),
    supplier_status: str | None = Query(None, alias="status", description="Filtrar por estatus"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    return service.get_suppliers(db, tenant_id, company_id, search, supplier_status)


@router.get("/suppliers/{supplier_id}", response_model=SupplierResponse)
def get_supplier(
    supplier_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"]
    return service.get_supplier(db, supplier_id, tenant_id, company_id)


@router.post("/suppliers", response_model=SupplierResponse, status_code=status.HTTP_201_CREATED)
def create_supplier(
    payload: SupplierCreate,
    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.create_supplier(db, payload, tenant_id, company_id, _user_id(current_user))


@router.patch("/suppliers/{supplier_id}", response_model=SupplierResponse)
def update_supplier(
    supplier_id: int,
    payload: SupplierUpdate,
    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_supplier(db, supplier_id, payload, tenant_id, company_id, _user_id(current_user))


@router.delete("/suppliers/{supplier_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_supplier(
    supplier_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_supplier(db, supplier_id, tenant_id, company_id)
