import { auth } from "~/lib/auth.server";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq } from "drizzle-orm";
import { isCommissioner } from "~/models/commissioner";
import { findUserById, getUserDisplayName } from "~/models/user";
import { getSocketIO } from "../../../server/socket";
import { startDraft } from "~/services/draft-autostart";

import type { ActionFunctionArgs } from "react-router";

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

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

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

  if (!seasonId) {
    return Response.json({ error: "Missing seasonId" }, { status: 400 });
  }

  const db = database();

  const season = await db.query.seasons.findFirst({
    where: eq(schema.seasons.id, seasonId),
  });

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

  if (!(await isCommissioner(season.leagueId, userId))) {
    return Response.json({ error: "Only commissioners can start the draft" }, { status: 403 });
  }

  const user = await findUserById(userId);
  const actorDisplayName = user ? (getUserDisplayName(user) ?? userId) : userId;

  const result = await startDraft({
    seasonId,
    actorUserId: userId,
    actorDisplayName,
    db,
    io: getSocketIO(),
  });

  if (!result.success) {
    const status =
      result.error === "Draft already started or completed" ? 400
      : result.error === "No draft slots found for this season" ? 400
      : 500;
    return Response.json({ error: result.error }, { status });
  }

  return Response.json({ success: true });
}
