import { requireUser } from "../../utils/auth"; import { getActiveCooldown, resolveCooldown } from "../../db/cooldown"; import { getProfile } from "../../db/profile"; /** * GET /api/protection/state * Combined protection + cooldown state polled every 30 s by the app. */ export default defineEventHandler(async (event) => { const user = await requireUser(event); const [cooldown, profile] = await Promise.all([ getActiveCooldown(user.id), getProfile(user.id), ]); const now = new Date(); let active = false; let remainingSeconds = 0; let cooldownEndsAt: string | null = null; if (cooldown) { const expired = now >= cooldown.cooldownEndsAt; if (expired) { await resolveCooldown(cooldown.id); // After resolve: no active cooldown } else { active = true; remainingSeconds = Math.max( 0, Math.floor((cooldown.cooldownEndsAt.getTime() - now.getTime()) / 1000), ); cooldownEndsAt = cooldown.cooldownEndsAt.toISOString(); } } const plan = (profile?.plan ?? "free") as "free" | "pro" | "legend"; return { success: true, data: { protectionShouldBeActive: !active, cooldown: { active, remainingSeconds, cooldownEndsAt, }, plan, }, }; });