// app/api/feature-flags/route.ts
import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';

const BASE = 'https://statsigapi.net';
const API_KEY = process.env.STATSIG_CONSOLE_API_KEY!;
const API_VERSION = '20240601';

// Adhere to Statsig Console API gate schema (subset)
type StatsigGate = {
  id: string;
  name?: string;
  description?: string | null;
  idType?: string;
  lastModifierID?: string | null;
  lastModifiedTime?: number; // epoch ms
  lastModifierName?: string | null;
  lastModifierEmail?: string | null;
  creatorID?: string | null;
  createdTime?: number | null;
  creatorName?: string | null;
  creatorEmail?: string | null;
  targetApps?: string[];
  holdoutIDs?: string[];
  tags?: string[];
  isEnabled?: boolean;
  status?: string | null; // e.g., "Launched", "Disabled", "In Progress"
  rules?: unknown[]; // not used for now
  checksPerHour?: number;
  type?: string;
  typeReason?: string;
  team?: { id?: string; name?: string } | null;
  reviewSettings?: unknown;
  measureMetricLifts?: boolean;
  owner?: {
    ownerID?: string;
    ownerName?: string | null;
    ownerType?: string | null;
    ownerEmail?: string | null;
  } | null;
  monitoringMetrics?: unknown[];
  version?: number;
};

export async function GET(req: Request) {
  // Check authentication with Clerk
  const { userId, sessionClaims } = await auth();

  const email = sessionClaims?.['https://suno.ai/claims/email'] as string;
  if (
    !userId ||
    !email ||
    !(email?.endsWith('@suno.ai') || email?.endsWith('@suno.com'))
  ) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const { searchParams } = new URL(req.url);
  //   const teamId = searchParams.get('teamId') ?? undefined;
  const limit = Number(searchParams.get('limit') ?? 1000); // 1 large page
  const page = 1;

  const fetchJSON = async <T>(path: string) => {
    const r = await fetch(`${BASE}${path}`, {
      headers: {
        'STATSIG-API-KEY': API_KEY,
        'STATSIG-API-VERSION': API_VERSION,
      },
      cache: 'no-store',
    });
    if (!r.ok) throw new Error(`${path} failed: ${r.status} ${await r.text()}`);
    return r.json() as Promise<T>;
  };

  // 1) One big page of gates
  const gatesRes = await fetchJSON<{ data: StatsigGate[] }>(
    `/console/v1/gates?limit=${limit}&page=${page}`
  );
  const gates = gatesRes.data ?? [];

  //   const inTeam = teamId
  //     ? gates.filter((g) => (g.team?.id ?? null) === teamId)
  //     : gates;

  const ownerId = (g: StatsigGate) => g.owner?.ownerID || 'unassigned';

  const byOwner = new Map<string, StatsigGate[]>();
  for (const g of gates) {
    const k = ownerId(g)!;
    if (!byOwner.has(k)) byOwner.set(k, []);
    byOwner.get(k)!.push(g);
  }

  const owners = [...byOwner.entries()]
    .map(([oid, flags]) => {
      const label =
        oid === 'unassigned'
          ? 'Unassigned'
          : flags[0]?.owner?.ownerName || flags[0]?.owner?.ownerEmail || oid;
      flags.sort((a, b) => (a.name || '').localeCompare(b.name || ''));

      // Normalize to client-friendly shape
      const normalizedFlags = flags
        .map((g) => ({
          ...g,
          id: g.id,
          name: g.name,
          description: g.description ?? undefined,
          // keep client field names for backward-compat
          is_enabled: g.isEnabled ?? undefined,
          state: g.status ?? undefined,
          updated_at: g.lastModifiedTime
            ? new Date(g.lastModifiedTime).toISOString()
            : undefined,
          tags: g.tags ?? [],
        }))
        .sort(
          (a, b) => -(b.updated_at || '').localeCompare(a.updated_at || '')
        );

      return { ownerId: oid, ownerLabel: label, flags: normalizedFlags };
    })
    .sort((a, b) => a.ownerLabel.localeCompare(b.ownerLabel));

  // Heads-up if we likely truncated
  const maybeTruncated = gates.length >= limit;

  return NextResponse.json({
    owners,
    count: gates.length,
    maybeTruncated,
    limitUsed: limit,
  });
}
