import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { canManageWorkspace } from "@/lib/developers/auth";
import { listGmailMessages } from "@/lib/integrations/google-workspace";
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", "gmail")
      .maybeSingle();

    if (!connection) {
      return NextResponse.json({ error: "Gmail 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 url = new URL(req.url);
    const limit = Number(url.searchParams.get("limit") || 12);
    const messages = await listGmailMessages(
      admin,
      connection as IntegrationConnection & { secret_encrypted: string },
      Number.isFinite(limit) ? limit : 12
    );

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