"""Endpoint de retroalimentación ciudadana.

Reglas:
- El user_id se toma del token (nunca del body).
- target_unit_id es la UNIDAD (camión), no el chofer.
- La inserción usa supabase_admin (service_role) que bypassea RLS.
"""
from fastapi import APIRouter, Depends, HTTPException

from app.core.deps import get_current_user
from app.core.supabase_client import supabase_admin
from app.schemas.feedback import FeedbackCreate, FeedbackOut

router = APIRouter(prefix="/feedback", tags=["feedback"])


@router.post("", response_model=FeedbackOut, status_code=201)
def create_feedback(
    body: FeedbackCreate,
    current_user: dict = Depends(get_current_user),
):
    user_id = current_user["user_id"]

    # Validar que la unidad exista si se envió
    if body.target_unit_id is not None:
        try:
            unit = (
                supabase_admin.table("units")
                .select("id")
                .eq("id", body.target_unit_id)
                .limit(1)
                .execute()
            )
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"Error al validar unidad: {e}")
        if not unit.data:
            raise HTTPException(status_code=400, detail="Unidad inexistente")

    payload = {
        "user_id": user_id,
        "address_id": body.address_id,
        "type": body.type,
        "target_unit_id": body.target_unit_id,
        "message": body.message,
        "rating": body.rating,
    }

    try:
        res = supabase_admin.table("feedback").insert(payload).execute()
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error al guardar feedback: {e}")

    row = (res.data or [{}])[0]
    return FeedbackOut(
        id=str(row.get("id")),
        user_id=str(row.get("user_id")),
        address_id=row.get("address_id") and str(row["address_id"]),
        type=row.get("type") or body.type,
        target_unit_id=row.get("target_unit_id"),
        message=row.get("message"),
        rating=row.get("rating"),
        created_at=row.get("created_at") and str(row["created_at"]),
    )


@router.get("/me", response_model=list[FeedbackOut])
def my_feedback(current_user: dict = Depends(get_current_user)):
    try:
        res = (
            supabase_admin.table("feedback")
            .select("*")
            .eq("user_id", current_user["user_id"])
            .order("created_at", desc=True)
            .execute()
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error al listar feedback: {e}")

    out: list[FeedbackOut] = []
    for row in res.data or []:
        out.append(
            FeedbackOut(
                id=str(row.get("id")),
                user_id=str(row.get("user_id")),
                address_id=row.get("address_id") and str(row["address_id"]),
                type=row.get("type") or "",
                target_unit_id=row.get("target_unit_id"),
                message=row.get("message"),
                rating=row.get("rating"),
                created_at=row.get("created_at") and str(row["created_at"]),
            )
        )
    return out
