import { NextResponse } from "next/server";
import { currentUser } from "@/lib/auth";
import { getVerifiedPhone } from "@/lib/sms-pin";
import { getVerifiedEmail } from "@/lib/email-pin";
import { getBotHistory } from "@/lib/bot-api";

export const dynamic = "force-dynamic";

/**
 * Order/booking history for the cabinet (§10.3): only for an authorized user
 * with a verified phone; the bot endpoint trusts this backend, so the phone
 * is never accepted from the browser.
 */
export async function GET() {
  const user = await currentUser();
  if (!user) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
  const [phone, email] = await Promise.all([getVerifiedPhone(user.id), getVerifiedEmail(user.id)]);
  if (!phone) return NextResponse.json({ verified: false, phone: null, email, emailVerified: Boolean(email), orders: [], bookings: [] }, { headers: { "Cache-Control": "no-store" } });
  try {
    const history = await getBotHistory(phone);
    return NextResponse.json({ verified: true, phone, email, emailVerified: Boolean(email), orders: history.orders || [], bookings: history.bookings || [] }, { headers: { "Cache-Control": "no-store" } });
  } catch {
    return NextResponse.json({ verified: true, phone, email, emailVerified: Boolean(email), orders: [], bookings: [], error: "history_unavailable" }, { status: 200, headers: { "Cache-Control": "no-store" } });
  }
}
