import { getAuth } from "@clerk/react-router/server";
import { eq } from "drizzle-orm";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { isCommissioner } from "~/models/commissioner";
import { getSocketIO } from "../../../server/socket";
import { logger } from "~/lib/logger";

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;

  if (!seasonId) {
    return Response.json({ error: "Season ID is required" }, { status: 400 });
  }

  const db = database();

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

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

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

  // Check if draft is active
  if (season.status !== "draft") {
    return Response.json({ error: "Draft is not active" }, { status: 400 });
  }

  // Resume the draft
  await db
    .update(schema.seasons)
    .set({ draftPaused: false })
    .where(eq(schema.seasons.id, seasonId));

  // Emit socket event
  try {
    getSocketIO().to(`draft-${seasonId}`).emit("draft-resumed", {
      seasonId,
      paused: false,
    });
  } catch (error) {
    logger.error("Socket.IO error:", error);
  }

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