import { auth } from "~/lib/auth.server";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq } from "drizzle-orm";
import { addToWatchlist, removeFromWatchlist, isOnWatchlist, getTeamWatchlist } from "~/models/watchlist";
import { getSocketIO } from "../../../server/socket";

import type { ActionFunctionArgs } from "react-router";
export async function action(args: ActionFunctionArgs) {
  const { request } = args;
  const session = await auth.api.getSession({ headers: args.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");
  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();

  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 });
  }

  const alreadyWatched = await isOnWatchlist(teamId as string, participantId as string);

  if (alreadyWatched) {
    await removeFromWatchlist({ seasonId: seasonId as string, teamId: teamId as string, participantId: participantId as string });
  } else {
    await addToWatchlist({
      seasonId: seasonId as string,
      teamId: teamId as string,
      participantId: participantId as string,
    });
  }

  const updatedWatchlist = await getTeamWatchlist(teamId as string, seasonId as string);
  const participantIds = updatedWatchlist.map((item) => item.participantId);

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

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