import { auth } from "~/lib/auth.server";
import type { Route } from "./+types/api.admin.export-sports-data";
import { isUserAdmin } from "~/models/user";
import { exportSportsDataToJSON } from "~/utils/sports-data-sync.server";

export async function loader(args: Route.LoaderArgs) {
  const session = await auth.api.getSession({ headers: args.request.headers });
  const userId = session?.user.id ?? null;

  if (!userId) {
    throw new Response("Unauthorized", { status: 401 });
  }

  const isAdmin = await isUserAdmin(userId);
  if (!isAdmin) {
    throw new Response("Forbidden", { status: 403 });
  }

  const data = await exportSportsDataToJSON();

  return Response.json(data);
}
