import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { db, userUsage, auditLogs, eq, and } from "@epicure/db";
import { randomUUID } from "crypto";

interface RouteContext {
  params: Promise<{ id: string }>;
}

function currentMonth() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}

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

  const { id } = await params;
  const month = currentMonth();

  // Only aiCallsUsed is a resettable monthly counter — recipe count and
  // storage usage are lifetime totals derived live from real data (recipes,
  // photos, avatar), so there's nothing to reset there.
  const [updated] = await db
    .update(userUsage)
    .set({ aiCallsUsed: 0 })
    .where(and(eq(userUsage.userId, id), eq(userUsage.month, month)))
    .returning();

  await db.insert(auditLogs).values({
    id: randomUUID(),
    userId: session!.user.id,
    action: "admin.user.reset_usage",
    targetType: "user",
    targetId: id,
    metadata: JSON.stringify({ month }),
    createdAt: new Date(),
  });

  return NextResponse.json({ usage: updated ?? { userId: id, month, aiCallsUsed: 0 } });
}
