from fastapi import APIRouter, Depends, File, Query, Response, UploadFile, status
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user

from . import pdf_service, service
from .dto import (
    QuoteCreate,
    QuoteItemCreate,
    QuoteItemResponse,
    QuoteItemUpdate,
    QuoteResponse,
    QuoteSettingsInput,
    QuoteSettingsResponse,
    QuoteUpdate,
    SendQuoteEmailRequest,
)

router = APIRouter()


# ----- Configuración de marca del formato de cotización -----

@router.get("/quote-settings", response_model=QuoteSettingsResponse)
def get_quote_settings(
    company_id: int = Query(...),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    obj = pdf_service.get_settings(db, current_user["tenant_id"], company_id)
    return obj or QuoteSettingsResponse()


@router.put("/quote-settings", response_model=QuoteSettingsResponse)
def save_quote_settings(
    payload: QuoteSettingsInput,
    company_id: int = Query(...),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return pdf_service.upsert_settings(db, current_user["tenant_id"], company_id, payload.model_dump(exclude_unset=True))


@router.post("/quote-settings/logo", response_model=QuoteSettingsResponse)
async def upload_quote_logo(
    company_id: int = Query(...),
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    from core.storage_s3 import put_object_bytes
    tenant_id = current_user["tenant_id"]
    content = await file.read()
    safe = (file.filename or "logo").replace("/", "-")
    key = f"tenants/{tenant_id}/companies/{company_id}/crm-quote-logo/{safe}"
    put_object_bytes(key, content, content_type=file.content_type or "image/png")
    return pdf_service.set_logo_key(db, tenant_id, company_id, key)


@router.get("/quote-settings/logo-url")
def get_logo_url(
    company_id: int = Query(...),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    from core.storage_s3 import presigned_get_url
    obj = pdf_service.get_settings(db, current_user["tenant_id"], company_id)
    if not obj or not obj.logo_file_key:
        return {"url": None}
    return {"url": presigned_get_url(obj.logo_file_key)}


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


@router.get("/quotes", response_model=list[QuoteResponse])
def list_quotes(
    company_id: int = Query(..., description="Company ID"),
    search: str | None = Query(None),
    quote_status: str | None = Query(None, alias="status"),
    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_quotes(db, tenant_id, company_id, search, quote_status, account_id)


@router.get("/quotes/{quote_id}", response_model=QuoteResponse)
def get_quote(
    quote_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_quote(db, quote_id, tenant_id, company_id)


@router.post("/quotes", response_model=QuoteResponse, status_code=status.HTTP_201_CREATED)
def create_quote(
    payload: QuoteCreate,
    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_quote(db, payload, tenant_id, company_id, _user_id(current_user))


@router.post(
    "/quotes/from-service-request",
    response_model=list[QuoteResponse],
    status_code=status.HTTP_201_CREATED,
)
def create_quotes_from_service_request(
    service_request_id: int = Query(..., description="Solicitud de servicio a cotizar"),
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Genera la(s) cotización(es) desde una solicitud. Si es 'Ambas' devuelve 2 (FCL/LCL)."""
    tenant_id = current_user["tenant_id"]
    return service.create_quotes_from_service_request(
        db, service_request_id, tenant_id, company_id, _user_id(current_user)
    )


@router.patch("/quotes/{quote_id}", response_model=QuoteResponse)
def update_quote(
    quote_id: int,
    payload: QuoteUpdate,
    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_quote(db, quote_id, payload, tenant_id, company_id, _user_id(current_user))


@router.patch("/quotes/{quote_id}/send", response_model=QuoteResponse)
def send_quote(
    quote_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return service.send_quote(db, quote_id, current_user["tenant_id"], company_id)


@router.patch("/quotes/{quote_id}/accept", response_model=QuoteResponse)
def accept_quote(
    quote_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return service.accept_quote(db, quote_id, current_user["tenant_id"], company_id)


@router.patch("/quotes/{quote_id}/reject", response_model=QuoteResponse)
def reject_quote(
    quote_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return service.reject_quote(db, quote_id, current_user["tenant_id"], company_id)


@router.get("/quotes/{quote_id}/pdf")
def quote_pdf(
    quote_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Devuelve el PDF de la cotización directamente (vía backend, sin exponer MinIO)."""
    tenant_id = current_user["tenant_id"]
    quote = service.get_quote(db, quote_id, tenant_id, company_id)
    pdf_bytes = pdf_service.build_pdf_bytes(db, quote, tenant_id, company_id)
    ref = (quote.reference or f"cot-{quote.id}").replace("/", "-")
    return Response(
        content=pdf_bytes,
        media_type="application/pdf",
        headers={"Content-Disposition": f'inline; filename="cotizacion-{ref}.pdf"'},
    )


@router.post("/quotes/{quote_id}/send-email")
async def quote_send_email(
    quote_id: int,
    payload: SendQuoteEmailRequest,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Genera el PDF y lo envía por correo (al cliente o al destinatario indicado)."""
    return await pdf_service.send_quote_email(
        db, quote_id, current_user["tenant_id"], company_id, payload.to, payload.subject, payload.message
    )


@router.post("/quotes/{quote_id}/clone", response_model=QuoteResponse, status_code=status.HTTP_201_CREATED)
def clone_quote(
    quote_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Clona la cotización como borrador para re-cotizar (R-C-12)."""
    return service.clone_quote(db, quote_id, current_user["tenant_id"], company_id, _user_id(current_user))


@router.delete("/quotes/{quote_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_quote(
    quote_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    service.delete_quote(db, quote_id, current_user["tenant_id"], company_id)


# ----- Conceptos de la cotización -----

@router.get("/quotes/{quote_id}/items", response_model=list[QuoteItemResponse])
def list_quote_items(
    quote_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return service.get_quote_items(db, quote_id, current_user["tenant_id"], company_id)


@router.post("/quote-items", response_model=QuoteItemResponse, status_code=status.HTTP_201_CREATED)
def create_quote_item(
    payload: QuoteItemCreate,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return service.create_quote_item(db, payload, current_user["tenant_id"], company_id)


@router.patch("/quote-items/{item_id}", response_model=QuoteItemResponse)
def update_quote_item(
    item_id: int,
    payload: QuoteItemUpdate,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    return service.update_quote_item(db, item_id, payload, current_user["tenant_id"], company_id)


@router.delete("/quote-items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_quote_item(
    item_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    service.delete_quote_item(db, item_id, current_user["tenant_id"], company_id)
