import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { canManageWorkspace } from "@/lib/developers/auth";
import {
  buildGoogleCalendarConnectUrl,
  createGoogleCalendarState,
  getGoogleCalendarRedirectUri,
} from "@/lib/integrations/google-calendar";
import { createRouteClient } from "@/lib/supabase/route";

export async function GET(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      const loginUrl = new URL("/login", new URL(req.url).origin);
      return NextResponse.redirect(loginUrl);
    }

    const url = new URL(req.url);
    const teamId = url.searchParams.get("teamId");
    const manageable = await canManageWorkspace(user.id, teamId);

    if (!manageable) {
      return NextResponse.redirect(
        new URL("/integrations?googleCalendar=forbidden", new URL(req.url).origin)
      );
    }

    const redirectUri = getGoogleCalendarRedirectUri(new URL(req.url).origin);
    const state = createGoogleCalendarState({
      userId: user.id,
      teamId,
      issuedAt: Date.now(),
    });

    return NextResponse.redirect(
      buildGoogleCalendarConnectUrl({
        state,
        redirectUri,
      })
    );
  } catch (error) {
    logApiError("Google Calendar connect error:", error);
    return NextResponse.redirect(
      new URL("/integrations?googleCalendar=not_configured", new URL(req.url).origin)
    );
  }
}
