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 AddressCreate, AddressResponse, AddressUpdate

router = APIRouter()


@router.get("/addresses", response_model=list[AddressResponse])
def list_addresses(
    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_addresses(db, tenant_id, company_id, account_id, supplier_id)


@router.post("/addresses", response_model=AddressResponse, status_code=status.HTTP_201_CREATED)
def create_address(
    payload: AddressCreate,
    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_address(db, payload, tenant_id, company_id)


@router.patch("/addresses/{address_id}", response_model=AddressResponse)
def update_address(
    address_id: int,
    payload: AddressUpdate,
    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_address(db, address_id, payload, tenant_id, company_id)


@router.delete("/addresses/{address_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_address(
    address_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_address(db, address_id, tenant_id, company_id)
