import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireAdmin } from "@/lib/api-auth";
import { getFeatureFlagMatrix, setFeatureFlag, FEATURE_KEYS, TIERS } from "@/lib/feature-flags";

export async function GET() {
  const { response } = await requireAdmin();
  if (response) return response;

  const matrix = await getFeatureFlagMatrix();
  return NextResponse.json(matrix);
}

const UpdateBody = z.object({
  featureKey: z.enum(FEATURE_KEYS as [string, ...string[]]),
  tier: z.enum(TIERS as [string, ...string[]]),
  enabled: z.boolean(),
});

export async function PATCH(req: NextRequest) {
  const { session, response } = await requireAdmin();
  if (response) return response;

  const body = (await req.json()) as unknown;
  const parsed = UpdateBody.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
  }

  await setFeatureFlag(
    parsed.data.featureKey as (typeof FEATURE_KEYS)[number],
    parsed.data.tier as (typeof TIERS)[number],
    parsed.data.enabled,
    session!.user.id
  );

  return NextResponse.json({ ok: true });
}
