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 ContactCreate, ContactResponse, ContactUpdate

router = APIRouter()


@router.get("/contacts", response_model=list[ContactResponse])
def list_contacts(
    company_id: int = Query(..., description="Company ID"),
    search: str | None = Query(None, description="Búsqueda por nombre o email"),
    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_contacts(db, tenant_id, company_id, search, account_id, supplier_id)


@router.get("/contacts/{contact_id}", response_model=ContactResponse)
def get_contact(
    contact_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_contact(db, contact_id, tenant_id, company_id)


@router.post("/contacts", response_model=ContactResponse, status_code=status.HTTP_201_CREATED)
def create_contact(
    payload: ContactCreate,
    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_contact(db, payload, tenant_id, company_id)


@router.patch("/contacts/{contact_id}", response_model=ContactResponse)
def update_contact(
    contact_id: int,
    payload: ContactUpdate,
    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_contact(db, contact_id, payload, tenant_id, company_id)


@router.delete("/contacts/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_contact(
    contact_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_contact(db, contact_id, tenant_id, company_id)
