import { getAuth } from "@clerk/react-router/server";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq } from "drizzle-orm";
import { addToQueue, getTeamQueue, isParticipantInQueue } from "~/models/draft-queue";
import { getSocketIO } from "../../../server/socket";

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");
  const teamId = formData.get("teamId");
  const participantId = formData.get("participantId");

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

  const db = database();

  // Verify user owns this team
  const team = await db.query.teams.findFirst({
    where: eq(schema.teams.id, teamId as string),
  });

  if (!team || team.ownerId !== userId) {
    return Response.json({ error: "Unauthorized" }, { status: 403 });
  }

  // Check if participant is already in queue
  const alreadyInQueue = await isParticipantInQueue(teamId as string, participantId as string);
  if (alreadyInQueue) {
    return Response.json({ error: "Participant already in queue" }, { status: 400 });
  }

  // Get current queue to determine position
  const currentQueue = await getTeamQueue(teamId as string);
  const queuePosition = currentQueue.length + 1;

  // Add to queue
  const queueItem = await addToQueue({
    seasonId: seasonId as string,
    teamId: teamId as string,
    participantId: participantId as string,
    queuePosition,
  });

  const updatedQueue = await getTeamQueue(teamId as string);
  const io = getSocketIO();
  io.to(`team-${teamId}`).emit("queue-updated", { queue: updatedQueue });

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