79 lines
2.1 KiB
TypeScript
79 lines
2.1 KiB
TypeScript
import { getAuth } from "@clerk/react-router/server";
|
|
import { database } from "~/database/context";
|
|
import * as schema from "~/database/schema";
|
|
import { eq, and } from "drizzle-orm";
|
|
import { getSocketIO } from "~/server/socket";
|
|
|
|
export async function action(args: any) {
|
|
const { request } = args;
|
|
const auth = await getAuth(args);
|
|
const userId = (auth as any).userId as string | null;
|
|
|
|
if (!userId) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const formData = await request.formData();
|
|
const seasonId = formData.get("seasonId") as string;
|
|
const teamId = formData.get("teamId") as string;
|
|
const isEnabled = formData.get("isEnabled") === "true";
|
|
const mode = formData.get("mode") as "next_pick" | "while_on";
|
|
|
|
if (!seasonId || !teamId || !mode) {
|
|
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),
|
|
});
|
|
|
|
if (!team || team.ownerId !== userId) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 403 });
|
|
}
|
|
|
|
// Check if autodraft settings exist
|
|
const existingSettings = await db.query.autodraftSettings.findFirst({
|
|
where: and(
|
|
eq(schema.autodraftSettings.seasonId, seasonId),
|
|
eq(schema.autodraftSettings.teamId, teamId)
|
|
),
|
|
});
|
|
|
|
let settings;
|
|
if (existingSettings) {
|
|
// Update existing settings
|
|
[settings] = await db
|
|
.update(schema.autodraftSettings)
|
|
.set({
|
|
isEnabled,
|
|
mode,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(schema.autodraftSettings.id, existingSettings.id))
|
|
.returning();
|
|
} else {
|
|
// Create new settings
|
|
[settings] = await db
|
|
.insert(schema.autodraftSettings)
|
|
.values({
|
|
seasonId,
|
|
teamId,
|
|
isEnabled,
|
|
mode,
|
|
})
|
|
.returning();
|
|
}
|
|
|
|
// Emit socket event to notify all clients in the draft room
|
|
const io = getSocketIO();
|
|
io.to(`draft-${seasonId}`).emit("autodraft-updated", {
|
|
teamId,
|
|
isEnabled,
|
|
mode,
|
|
});
|
|
|
|
return Response.json({ success: true, settings });
|
|
}
|