import { requireUser } from "../../utils/auth";
import {
  appendProtectionEventDeduped,
  type ProtectionSource,
} from "../../db/protectionStateLog";

const VALID_SOURCES: ProtectionSource[] = ["vpn", "mdm", "client"];

/**
 * POST /api/protection/event
 *
 * Body: { active: boolean, source: 'vpn' | 'mdm' | 'client' }
 *
 * Called from the native app (useProtectionState / lib/protection) when the
 * combined protection state transitions on↔off. The client deduplicates
 * locally (only fires on real transitions); the server deduplicates again
 * against the last DB row for the user.
 *
 * Returns { success: true, written: true } if a new row was written,
 *         { success: true, written: false } if deduplicated (state unchanged).
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);

  if (typeof body?.active !== "boolean") {
    throw createError({ statusCode: 400, message: "active (boolean) required" });
  }

  const source: ProtectionSource = VALID_SOURCES.includes(body.source)
    ? (body.source as ProtectionSource)
    : "client";

  const row = await appendProtectionEventDeduped(user.id, body.active, source);

  return { success: true, written: row !== null };
});
