"""
Internal API — endpoints consumed by other stack apps (not public).
nginx denies /kitchen/api/internal/ from the public side; these endpoints
are called directly on the backend port (8000) from within the docker bridge.
"""
from datetime import date
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from database import get_db
from auth import verify_internal_secret
from models.resos import ResosBooking

router = APIRouter()


@router.get("/api/internal/resos/bookings")
async def internal_resos_bookings(
    booking_date: Optional[str] = Query(None, alias="date"),
    _: None = Depends(verify_internal_secret),
    db: AsyncSession = Depends(get_db),
):
    """
    Cached ResOS bookings for a given date — consumed by the KDS app bookings screen.
    KDS calls: GET http://10.10.10.110:8000/api/internal/resos/bookings?date=YYYY-MM-DD
    Authorization: Bearer {STACK_INTERNAL_SECRET}
    """
    try:
        target_date = date.fromisoformat(booking_date) if booking_date else date.today()
    except (ValueError, TypeError):
        raise HTTPException(status_code=400, detail="Invalid date format — use YYYY-MM-DD")

    result = await db.execute(
        select(ResosBooking)
        .where(
            ResosBooking.kitchen_id == 1,
            ResosBooking.booking_date == target_date,
        )
        .order_by(ResosBooking.booking_time)
    )
    bookings = result.scalars().all()

    return [
        {
            "id": b.id,
            "resos_booking_id": b.resos_booking_id,
            "booking_date": b.booking_date.isoformat(),
            "booking_time": b.booking_time.strftime("%H:%M"),
            "people": b.people,
            "status": b.status,
            "seating_area": b.seating_area,
            "table_name": b.table_name,
            "hotel_booking_number": b.hotel_booking_number,
            "is_hotel_guest": b.is_hotel_guest,
            "is_dbb": b.is_dbb,
            "allergies": b.allergies,
            "notes": b.notes,
            "opening_hour_name": b.opening_hour_name,
        }
        for b in bookings
    ]
