import type { ActionFunctionArgs } from "react-router";
import { auth } from "~/lib/auth.server";
import { updateUser, isUserInActiveDraft } from "~/models/user";
import { TIMEZONE_OPTIONS } from "~/components/league/TimezoneSelect";

const VALID_TIMEZONES = new Set(
  TIMEZONE_OPTIONS.flatMap((g) => g.zones.map((z) => z.value))
);

export async function action(args: ActionFunctionArgs) {
  const session = await auth.api.getSession({ headers: args.request.headers });
  if (!session) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }

  const formData = await args.request.formData();
  const timezone = formData.get("timezone") as string | null;

  if (!timezone || !VALID_TIMEZONES.has(timezone)) {
    return Response.json({ error: "Invalid timezone" }, { status: 400 });
  }

  if (await isUserInActiveDraft(session.user.id)) {
    return Response.json(
      { error: "Cannot change timezone during an active draft" },
      { status: 403 }
    );
  }

  await updateUser(session.user.id, { timezone });
  return Response.json({ success: true });
}
