Files
peworkshop/app/api/hunt/timer/route.js
T

189 lines
5.4 KiB
JavaScript

import { query, queryOne, run } from "@/lib/db";
import { cookies } from "next/headers";
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
export const dynamic = "force-dynamic"; // Disable caching
// Helper function to ensure the hunt_timer table exists
async function ensureTableExists() {
try {
// Check if the table exists by querying it
await queryOne("SELECT name FROM sqlite_master WHERE type='table' AND name='hunt_timer'");
// If no error was thrown, the table exists
return true;
} catch (error) {
console.error("Error checking for hunt_timer table:", error);
// Try to create the table
try {
await run(`
CREATE TABLE IF NOT EXISTS hunt_timer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
active INTEGER NOT NULL DEFAULT 0,
start_time TEXT NOT NULL,
end_time TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
console.log("hunt_timer table created successfully");
return true;
} catch (createError) {
console.error("Failed to create hunt_timer table:", createError);
return false;
}
}
}
// GET endpoint to get current timer status
export async function GET(request) {
try {
// Verify the user is authenticated
const cookieStore = cookies();
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
if (!sessionToken) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const userData = verifyToken(sessionToken);
if (!userData) {
return Response.json({ error: "Invalid session" }, { status: 401 });
}
// Ensure the table exists
const tableExists = await ensureTableExists();
if (!tableExists) {
return Response.json(
{ error: "Database table not found" },
{ status: 500 }
);
}
// Get the current hunt timer status
const timerStatus = await queryOne(
"SELECT active, start_time, end_time FROM hunt_timer ORDER BY id DESC LIMIT 1"
);
if (!timerStatus) {
return Response.json({
active: false,
startTime: null,
endTime: null,
});
}
return Response.json({
active: !!timerStatus.active,
startTime: timerStatus.start_time,
endTime: timerStatus.end_time,
});
} catch (error) {
console.error("Error getting timer status:", error);
return Response.json(
{ error: "Failed to get timer status" },
{ status: 500 }
);
}
}
// POST endpoint to start/stop timer
export async function POST(request) {
try {
// Verify the user is authenticated and is an admin
const cookieStore = cookies();
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
if (!sessionToken) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const userData = verifyToken(sessionToken);
if (!userData) {
return Response.json({ error: "Invalid session" }, { status: 401 });
}
console.log("User role:", userData.role);
// Check if user is admin (more lenient check)
if (!(userData.role === "admin" || userData.isAdmin === true || userData.is_admin === 1)) {
return Response.json(
{ error: "Unauthorized: Admin access required" },
{ status: 403 }
);
}
// Ensure the table exists
const tableExists = await ensureTableExists();
if (!tableExists) {
return Response.json(
{ error: "Database table not found" },
{ status: 500 }
);
}
const body = await request.json();
const { action, endTime } = body;
console.log("Timer action:", action, "End time:", endTime);
if (action === "start") {
try {
// Get current time in ISO format
const startTime = new Date().toISOString();
// First, deactivate any existing timers
await run("UPDATE hunt_timer SET active = 0 WHERE active = 1");
// Insert new timer record
await run(
"INSERT INTO hunt_timer (active, start_time, end_time) VALUES (?, ?, ?)",
[1, startTime, endTime || null]
);
return Response.json({
success: true,
message: "Timer started successfully",
startTime,
endTime: endTime || null,
});
} catch (dbError) {
console.error("Database error starting timer:", dbError);
return Response.json(
{ error: "Database error: " + dbError.message },
{ status: 500 }
);
}
} else if (action === "stop") {
try {
// Update the most recent timer to inactive
await run(
"UPDATE hunt_timer SET active = 0, end_time = ? WHERE active = 1",
[new Date().toISOString()]
);
return Response.json({
success: true,
message: "Timer stopped successfully",
});
} catch (dbError) {
console.error("Database error stopping timer:", dbError);
return Response.json(
{ error: "Database error: " + dbError.message },
{ status: 500 }
);
}
} else {
return Response.json(
{ error: "Invalid action. Use 'start' or 'stop'." },
{ status: 400 }
);
}
} catch (error) {
console.error("Error managing timer:", error);
return Response.json({
error: "Failed to manage timer: " + error.message
}, { status: 500 });
}
}