import { NextResponse } from "next/server";
import { currentUser } from "@/lib/auth";
import { getVerifiedPhone } from "@/lib/sms-pin";
import { getVerifiedEmail } from "@/lib/email-pin";
import { getBotHistory, syncBotIdentity, getBotUnread } 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(request: Request) {
  const user = await currentUser();
  if (!user) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
  if (!user.profileCompletedAt) return NextResponse.json({ error: "profile_required" }, { status: 428 });
  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 {
    await syncBotIdentity(phone, user.customerRef);
    if (new URL(request.url).searchParams.has("summary")) return NextResponse.json(await getBotUnread(phone, user.customerRef), { headers: { "Cache-Control": "no-store" } });
    const page = Math.max(1, Math.min(Number(new URL(request.url).searchParams.get("page")) || 1, 10000));
    const history = await getBotHistory(phone, user.customerRef, Math.floor(page), new URLSearchParams([...new URL(request.url).searchParams].filter(([k]) => ["sort_by", "sort_dir", "section"].includes(k))).toString());
    return NextResponse.json({ verified: true, phone, email, emailVerified: Boolean(email), pagination: history.pagination, unread: history.unread, unread_sections: history.unread_sections, 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" } });
  }
}
