import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { canManageWorkspace } from "@/lib/developers/auth";
import { listGoogleCalendars } from "@/lib/integrations/google-calendar";
import { createAdminClient } from "@/lib/supabase/admin";
import { createRouteClient } from "@/lib/supabase/route";
import type { IntegrationConnection } from "@/types";

export async function GET(
  _req: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await context.params;
    const admin = createAdminClient();
    const { data: connection } = await admin
      .from("integration_connections")
      .select(
        "id, user_id, team_id, provider, name, config, event_types, is_active, last_delivery_at, last_response_status, last_error, created_at, updated_at, secret_encrypted"
      )
      .eq("id", id)
      .eq("provider", "google_calendar")
      .maybeSingle();

    if (!connection) {
      return NextResponse.json({ error: "Google Calendar connection not found" }, { status: 404 });
    }

    const manageable = await canManageWorkspace(user.id, connection.team_id || null);
    if (!manageable) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const calendars = await listGoogleCalendars(
      admin,
      connection as IntegrationConnection & { secret_encrypted: string }
    );

    return NextResponse.json({ calendars });
  } catch (error) {
    logApiError("Google Calendar calendars GET error:", error);
    return NextResponse.json(
      { error: "Failed to load Google calendars" },
      { status: 500 }
    );
  }
}
