import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { listUsers } from "@/lib/localDb";
import UsageClient from "./UsageClient";

export const dynamic = "force-dynamic";

async function getAdminData() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get("auth_token")?.value;
    if (!token) return { isAdmin: false, users: [], currentUser: null };
    const payload = await verifyToken(token);
    if (!payload) return { isAdmin: false, users: [], currentUser: null };

    const isAdmin = payload.role === "admin";
    let users = [];

    if (isAdmin) {
      users = await listUsers();
    }

    return {
      isAdmin,
      users,
      currentUser: { id: payload.userId, role: payload.role },
    };
  } catch {
    return { isAdmin: false, users: [], currentUser: null };
  }
}

export default async function UsagePage() {
  const { isAdmin, users, currentUser } = await getAdminData();
  return (
    <UsageClient isAdmin={isAdmin} users={users} currentUser={currentUser} />
  );
}
