import { getAuth } from "@clerk/react-router/server";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq } from "drizzle-orm";
import { removeFromQueue, getTeamQueue } 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 queueId = formData.get("queueId");
  const teamId = formData.get("teamId");

  if (!queueId || !teamId) {
    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 });
  }

  // Remove from queue
  await removeFromQueue(queueId as string);

  // Get updated queue
  const updatedQueue = await getTeamQueue(teamId as string);

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

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