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 LeadConvert, LeadConvertResult, LeadCreate, LeadResponse, LeadUpdate

router = APIRouter()


@router.get("/leads", response_model=list[LeadResponse])
def list_leads(
    company_id: int = Query(..., description="Company ID"),
    search: str | None = Query(None, description="Búsqueda por nombre, empresa o email"),
    lead_status: str | None = Query(None, alias="status", description="Filtrar por estado"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    return service.get_leads(db, tenant_id, company_id, search, lead_status)


@router.get("/leads/{lead_id}", response_model=LeadResponse)
def get_lead(
    lead_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_lead(db, lead_id, tenant_id, company_id)


@router.post("/leads", response_model=LeadResponse, status_code=status.HTTP_201_CREATED)
def create_lead(
    payload: LeadCreate,
    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_lead(db, payload, tenant_id, company_id)


@router.patch("/leads/{lead_id}", response_model=LeadResponse)
def update_lead(
    lead_id: int,
    payload: LeadUpdate,
    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_lead(db, lead_id, payload, tenant_id, company_id)


@router.post("/leads/{lead_id}/convert", response_model=LeadConvertResult)
def convert_lead(
    lead_id: int,
    payload: LeadConvert,
    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.convert_lead(db, lead_id, payload, tenant_id, company_id)


@router.delete("/leads/{lead_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_lead(
    lead_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_lead(db, lead_id, tenant_id, company_id)
