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 (
    RateRequestCreate,
    RateRequestResponse,
    RateRequestUpdate,
    ServiceRequestContactInput,
    ServiceRequestCreate,
    ServiceRequestFromOpportunityInput,
    ServiceRequestResponse,
    ServiceRequestUpdate,
)

router = APIRouter()


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


# ----- Solicitudes de servicio (RFQ) -----

@router.get("/service-requests", response_model=list[ServiceRequestResponse])
def list_service_requests(
    company_id: int = Query(..., description="Company ID"),
    search: str | None = Query(None),
    req_status: str | None = Query(None, alias="status"),
    operation_type: str | None = Query(None),
    account_id: int | None = Query(None),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    return service.get_service_requests(db, tenant_id, company_id, search, req_status, operation_type, account_id)


@router.get("/service-requests/{request_id}", response_model=ServiceRequestResponse)
def get_service_request(
    request_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_service_request(db, request_id, tenant_id, company_id)


@router.post("/service-requests", response_model=ServiceRequestResponse, status_code=status.HTTP_201_CREATED)
def create_service_request(
    payload: ServiceRequestCreate,
    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_service_request(db, payload, tenant_id, company_id, _user_id(current_user))


@router.patch("/service-requests/{request_id}", response_model=ServiceRequestResponse)
def update_service_request(
    request_id: int,
    payload: ServiceRequestUpdate,
    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_service_request(db, request_id, payload, tenant_id, company_id, _user_id(current_user))


@router.post("/service-requests/from-opportunity", response_model=ServiceRequestResponse, status_code=status.HTTP_201_CREATED)
def create_from_opportunity(
    payload: ServiceRequestFromOpportunityInput,
    opportunity_id: int = Query(..., description="Oportunidad a convertir en solicitud"),
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Convierte una oportunidad del embudo en solicitud/RFQ enlazada (R-C-02)."""
    tenant_id = current_user["tenant_id"]
    return service.create_from_opportunity(db, opportunity_id, payload, tenant_id, company_id, _user_id(current_user))


@router.post("/service-requests/{request_id}/contact", response_model=ServiceRequestResponse)
def register_contact(
    request_id: int,
    payload: ServiceRequestContactInput,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Registra el contacto al cliente como etapa del flujo comercial (R-C-04)."""
    tenant_id = current_user["tenant_id"]
    return service.register_contact(db, request_id, payload, tenant_id, company_id, _user_id(current_user))


@router.post("/service-requests/{request_id}/requote", response_model=ServiceRequestResponse)
def reopen_for_requote(
    request_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Reabre una solicitud rechazada para volver a cotizar (R-C-12)."""
    tenant_id = current_user["tenant_id"]
    return service.reopen_for_requote(db, request_id, tenant_id, company_id, _user_id(current_user))


@router.delete("/service-requests/{request_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_service_request(
    request_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_service_request(db, request_id, tenant_id, company_id)


# ----- Solicitudes de tarifa -----

@router.get("/rate-requests", response_model=list[RateRequestResponse])
def list_rate_requests(
    company_id: int = Query(..., description="Company ID"),
    service_request_id: int | None = Query(None),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    tenant_id = current_user["tenant_id"]
    return service.get_rate_requests(db, tenant_id, company_id, service_request_id)


@router.post("/rate-requests", response_model=RateRequestResponse, status_code=status.HTTP_201_CREATED)
def create_rate_request(
    payload: RateRequestCreate,
    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_rate_request(db, payload, tenant_id, company_id)


@router.patch("/rate-requests/{rate_id}", response_model=RateRequestResponse)
def update_rate_request(
    rate_id: int,
    payload: RateRequestUpdate,
    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_rate_request(db, rate_id, payload, tenant_id, company_id)


@router.delete("/rate-requests/{rate_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_rate_request(
    rate_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_rate_request(db, rate_id, tenant_id, company_id)
