/**
 * /api/admin/users
 *
 * GET    — list all users with usage stats
 * PATCH  — update user role / plan / usage_limit
 *
 * Admin-only. Verified via profiles.role check server-side.
 */

import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { isCsrfSafe, csrfForbiddenPayload } from "@/lib/csrf";

async function requireAdmin(supabase: ReturnType<typeof createClient>) {
  const { data: { user }, error } = await supabase.auth.getUser();
  if (error || !user) return null;

  const { data: profile } = await supabase
    .from("profiles")
    .select("role")
    .eq("id", user.id)
    .single();

  if (profile?.role !== "admin") return null;
  return user;
}

// ── GET — list users ──────────────────────────────────────────────────────────
export async function GET(request: NextRequest) {
  const supabase = createClient();
  const admin = await requireAdmin(supabase);
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get("page") ?? "1");
  const limit = parseInt(searchParams.get("limit") ?? "50");
  const search = searchParams.get("search") ?? "";
  const offset = (page - 1) * limit;

  let query = supabase
    .from("profiles")
    .select("*", { count: "exact" })
    .order("created_at", { ascending: false })
    .range(offset, offset + limit - 1);

  if (search) {
    query = query.or(`email.ilike.%${search}%,full_name.ilike.%${search}%`);
  }

  const { data: profiles, error, count } = await query;
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  // Fetch per-user generation stats
  const userIds = (profiles ?? []).map((p) => p.id);
  let historyStats: Record<string, number> = {};
  if (userIds.length > 0) {
    const { data: stats } = await supabase
      .from("prompt_history")
      .select("user_id")
      .in("user_id", userIds);

    historyStats = (stats ?? []).reduce((acc: Record<string, number>, row) => {
      acc[row.user_id] = (acc[row.user_id] ?? 0) + 1;
      return acc;
    }, {});
  }

  const enriched = (profiles ?? []).map((p) => ({
    ...p,
    total_generations: historyStats[p.id] ?? 0,
  }));

  return NextResponse.json({ data: enriched, count, page, limit });
}

// ── PATCH — update user (role, plan, usage_limit) ─────────────────────────────
export async function PATCH(request: NextRequest) {
  // Fix Issue B: CSRF check — admin mutations perlu proteksi CSRF
  if (!isCsrfSafe(request)) return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  const supabase = createClient();
  const admin = await requireAdmin(supabase);
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await request.json() as {
    id: string;
    role?: "user" | "admin";
    plan?: "free" | "pro" | "enterprise";
    usage_limit?: number;
  };

  if (!body.id) return NextResponse.json({ error: "User ID required" }, { status: 400 });

  const updates: Record<string, unknown> = {};
  if (body.role !== undefined)        updates.role = body.role;
  if (body.plan !== undefined)        updates.plan = body.plan;
  if (body.usage_limit !== undefined) updates.usage_limit = body.usage_limit;

  if (Object.keys(updates).length === 0) {
    return NextResponse.json({ error: "No fields to update" }, { status: 400 });
  }

  const { data, error } = await supabase
    .from("profiles")
    .update(updates)
    .eq("id", body.id)
    .select()
    .single();

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ data });
}
