import crypto from "crypto";
import { NextRequest, NextResponse } from "next/server";
import { hasPermission } from "@/lib/adminAuth";
import { getSessionClientId } from "@/lib/auth";
import { connectDB } from "@/lib/db";
import { Calendar } from "@/models/Calendar";
import { buildGoogleAuthUrl, isGoogleConfigured } from "@/lib/googleCalendar";
import { getSiteUrl } from "@/lib/seo";

const STATE_COOKIE = "google_oauth_state";

export async function GET(req: NextRequest) {
  const calendarId = req.nextUrl.searchParams.get("calendarId") || "";
  const locale = req.nextUrl.searchParams.get("locale") || "de";
  if (!isGoogleConfigured()) return new NextResponse("Google-Anbindung nicht konfiguriert.", { status: 501 });

  const clientId = await getSessionClientId();
  if (!clientId) return NextResponse.redirect(`${getSiteUrl()}/${locale}/login`);

  await connectDB();
  const cal = await Calendar.findById(calendarId).lean();
  if (!cal) return NextResponse.redirect(`${getSiteUrl()}/de/admin/calendar?googleError=notfound`);

  const authorized =
    cal.kind === "orders" ? await hasPermission("orders_edit") : (await hasPermission("calendars_edit")) && String(cal.ownerId) === clientId;
  if (!authorized) return NextResponse.redirect(`${getSiteUrl()}/de/admin/calendar?googleError=forbidden`);

  const nonce = crypto.randomBytes(16).toString("hex");
  const state = `${nonce}:${calendarId}`;

  const res = NextResponse.redirect(buildGoogleAuthUrl(state));
  res.cookies.set(STATE_COOKIE, state, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: 600,
  });
  return res;
}
