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 AccountCreate, AccountResponse, AccountUpdate

router = APIRouter()


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


@router.get("/accounts", response_model=list[AccountResponse])
def list_accounts(
    company_id: int = Query(..., description="Company ID"),
    search: str | None = Query(None, description="Búsqueda por nombre, nombre comercial o RFC"),
    account_status: str | None = Query(None, alias="status", description="Filtrar por estatus"),
    record_type: str | None = Query(None, description="Filtrar por tipo (cliente | prospecto)"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    return service.get_accounts(db, tenant_id, company_id, search, account_status, record_type)


@router.get("/accounts/{account_id}", response_model=AccountResponse)
def get_account(
    account_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_account(db, account_id, tenant_id, company_id)


@router.post("/accounts", response_model=AccountResponse, status_code=status.HTTP_201_CREATED)
def create_account(
    payload: AccountCreate,
    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_account(db, payload, tenant_id, company_id, _user_id(current_user))


@router.patch("/accounts/{account_id}", response_model=AccountResponse)
def update_account(
    account_id: int,
    payload: AccountUpdate,
    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_account(db, account_id, payload, tenant_id, company_id, _user_id(current_user))


@router.delete("/accounts/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_account(
    account_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_account(db, account_id, tenant_id, company_id)
