import { getAuth } from "@clerk/react-router/server";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq } from "drizzle-orm";
import { executeAutoPick } from "~/models/draft-utils";
import { isCommissioner } from "~/models/commissioner";

import type { ActionFunctionArgs } from "react-router";
export async function action(args: ActionFunctionArgs) {
  const { request } = args;
  const { userId } = await getAuth(args);

  if (!userId) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }

  const formData = await request.formData();
  const seasonId = formData.get("seasonId") as string;
  const teamId = formData.get("teamId") as string;
  const pickNumber = parseInt(formData.get("pickNumber") as string);

  if (!seasonId || !teamId || !pickNumber) {
    return Response.json({ error: "Missing required fields" }, { status: 400 });
  }

  const db = database();

  // Get season details to verify commissioner permissions
  const season = await db.query.seasons.findFirst({
    where: eq(schema.seasons.id, seasonId),
  });

  if (!season) {
    return Response.json({ error: "Season not found" }, { status: 404 });
  }

  // Check if user is commissioner
  if (!(await isCommissioner(season.leagueId, userId))) {
    return Response.json({ error: "Only commissioners can force autopick" }, { status: 403 });
  }

  // Execute the autopick using the unified function
  const result = await executeAutoPick({
    seasonId,
    teamId,
    pickNumber,
    triggeredBy: "commissioner",
    commissionerUserId: userId,
    db,
  });

  if (!result.success) {
    return Response.json({ error: result.error }, { status: 400 });
  }

  return Response.json({
    success: true,
    pick: result.pick,
    participant: result.participant,
    nextPickNumber: result.nextPickNumber,
    isDraftComplete: result.isDraftComplete,
  });
}
