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 { exchangeCodeForTokens } from "@/lib/googleCalendar";
import { runGoogleBackfillForCalendar } from "@/lib/googleSync";
import { getSiteUrl } from "@/lib/seo";

const STATE_COOKIE = "google_oauth_state";
const REDIRECT_BASE = "/de/admin/calendar";

export async function GET(req: NextRequest) {
  const code = req.nextUrl.searchParams.get("code");
  const state = req.nextUrl.searchParams.get("state");
  const cookieState = req.cookies.get(STATE_COOKIE)?.value;

  const fail = (reason: string) => NextResponse.redirect(`${getSiteUrl()}${REDIRECT_BASE}?googleError=${reason}`);

  if (!code || !state || !cookieState || state !== cookieState) return fail("state");

  const [, calendarId] = state.split(":");
  const clientId = await getSessionClientId();
  if (!clientId) return fail("auth");

  await connectDB();
  const cal = await Calendar.findById(calendarId).lean();
  if (!cal) return fail("notfound");

  const authorized =
    cal.kind === "orders" ? await hasPermission("orders_edit") : (await hasPermission("calendars_edit")) && String(cal.ownerId) === clientId;
  if (!authorized) return fail("forbidden");

  const tokens = await exchangeCodeForTokens(code);
  if (!tokens.access_token || !tokens.refresh_token) {
    // Kein Refresh-Token kommt z. B. zurück, wenn die App bereits einmal
    // verbunden war und Google beim erneuten Verbinden keinen neuen ausgibt —
    // durch "prompt=consent" im Auth-Request eigentlich immer vermieden.
    return fail("token");
  }

  await Calendar.findByIdAndUpdate(calendarId, {
    googleConnectedBy: clientId,
    googleAccessToken: tokens.access_token,
    googleRefreshToken: tokens.refresh_token,
    googleTokenExpiry: new Date(Date.now() + tokens.expires_in * 1000),
  });

  await runGoogleBackfillForCalendar(calendarId);

  const res = NextResponse.redirect(`${getSiteUrl()}${REDIRECT_BASE}?googleConnected=1`);
  res.cookies.delete(STATE_COOKIE);
  return res;
}
