"""Restaurant API routes."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query

from api.deps import get_admin_user
from core import restaurant, cache

router = APIRouter()


@router.get("")
def list_restaurants(
    limit: int = Query(100, le=500),
    offset: int = Query(0, ge=0),
    cuisine: str | None = None,
    region: str | None = None,
    channel: str | None = None,
):
    key = cache.make_key("restaurants", f"l={limit}", f"o={offset}", f"c={cuisine}", f"r={region}", f"ch={channel}")
    cached = cache.get(key)
    if cached is not None:
        return cached
    result = restaurant.get_all(limit=limit, offset=offset, cuisine=cuisine, region=region, channel=channel)
    cache.set(key, result)
    return result


@router.get("/{restaurant_id}")
def get_restaurant(restaurant_id: str):
    key = cache.make_key("restaurant", restaurant_id)
    cached = cache.get(key)
    if cached is not None:
        return cached
    r = restaurant.get_by_id(restaurant_id)
    if not r:
        raise HTTPException(404, "Restaurant not found")
    cache.set(key, r)
    return r


@router.put("/{restaurant_id}")
def update_restaurant(restaurant_id: str, body: dict, _admin: dict = Depends(get_admin_user)):
    from core.db import conn
    r = restaurant.get_by_id(restaurant_id)
    if not r:
        raise HTTPException(404, "Restaurant not found")

    allowed = ("name", "address", "region", "cuisine_type", "price_range",
               "phone", "website", "latitude", "longitude")
    sets = []
    params: dict = {"rid": restaurant_id}
    for field in allowed:
        if field in body:
            sets.append(f"{field} = :{field}")
            params[field] = body[field] if body[field] != "" else None
    if not sets:
        raise HTTPException(400, "No fields to update")
    sets.append("updated_at = SYSTIMESTAMP")
    sql = f"UPDATE restaurants SET {', '.join(sets)} WHERE id = :rid"
    with conn() as c:
        c.cursor().execute(sql, params)
    cache.flush()
    return {"ok": True}


@router.delete("/{restaurant_id}")
def delete_restaurant(restaurant_id: str, _admin: dict = Depends(get_admin_user)):
    from core.db import conn
    r = restaurant.get_by_id(restaurant_id)
    if not r:
        raise HTTPException(404, "Restaurant not found")
    with conn() as c:
        cur = c.cursor()
        cur.execute("DELETE FROM restaurant_vectors WHERE restaurant_id = :rid", {"rid": restaurant_id})
        cur.execute("DELETE FROM user_reviews WHERE restaurant_id = :rid", {"rid": restaurant_id})
        cur.execute("DELETE FROM video_restaurants WHERE restaurant_id = :rid", {"rid": restaurant_id})
        cur.execute("DELETE FROM restaurants WHERE id = :rid", {"rid": restaurant_id})
    cache.flush()
    return {"ok": True}


@router.get("/{restaurant_id}/videos")
def get_restaurant_videos(restaurant_id: str):
    key = cache.make_key("restaurant_videos", restaurant_id)
    cached = cache.get(key)
    if cached is not None:
        return cached
    r = restaurant.get_by_id(restaurant_id)
    if not r:
        raise HTTPException(404, "Restaurant not found")
    result = restaurant.get_video_links(restaurant_id)
    cache.set(key, result)
    return result
