import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import {
  getUsageByUser,
  getUsageSummary,
  getAllUsersUsage,
} from "@/lib/db/repos/usageRecordsRepo";

export const dynamic = "force-dynamic";

async function requireAdmin() {
  const cookieStore = await cookies();
  const token = cookieStore.get("auth_token")?.value;
  if (!token) return null;
  const payload = await verifyToken(token);
  if (!payload || payload.role !== "admin") return null;
  return payload;
}

async function getUserIdFromJwt() {
  const cookieStore = await cookies();
  const token = cookieStore.get("auth_token")?.value;
  if (!token) return null;
  const payload = await verifyToken(token);
  return payload?.userId || null;
}

// GET /api/usage — Query usage records with filters, pagination, and access control
export async function GET(request) {
  try {
    const { searchParams } = new URL(request.url);
    const startDate = searchParams.get("startDate") || undefined;
    const endDate = searchParams.get("endDate") || undefined;
    const model = searchParams.get("model") || undefined;
    const page = parseInt(searchParams.get("page") || "1", 10);
    const limit = parseInt(searchParams.get("limit") || "50", 10);

    const admin = await requireAdmin();

    if (admin) {
      // Admin: can query specific user or all users
      const requestedUserId = searchParams.get("userId");

      if (!requestedUserId) {
        // Admin querying all users' aggregate usage
        const allUsage = await getAllUsersUsage(startDate, endDate);
        return NextResponse.json({
          records: [],
          total: allUsage.length,
          page: 1,
          totalPages: 1,
          summary: {
            totalInputTokens: 0,
            totalOutputTokens: 0,
            totalTokens: 0,
            totalCost: 0,
            totalCreditUsed: 0,
            requestCount: 0,
            errorCount: 0,
          },
          allUsers: allUsage,
        });
      }

      // Admin querying a specific user's usage
      const result = await getUsageByUser(requestedUserId, {
        startDate,
        endDate,
        model,
        page,
        limit,
      });

      const summary = await getUsageSummary(requestedUserId, startDate, endDate);

      return NextResponse.json({
        ...result,
        summary,
      });
    }

    // Regular user: force userId from JWT, ignore any userId param
    const userId = await getUserIdFromJwt();
    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const result = await getUsageByUser(userId, {
      startDate,
      endDate,
      model,
      page,
      limit,
    });

    const summary = await getUsageSummary(userId, startDate, endDate);

    return NextResponse.json({
      ...result,
      summary,
    });
  } catch (error) {
    console.error("[usage] GET error:", error);
    return NextResponse.json(
      { error: "Failed to fetch usage records" },
      { status: 500 }
    );
  }
}
