import { requireUser } from "../../utils/auth";
import { usePrisma } from "../../utils/prisma";

/**
 * POST /api/protection/screentime-passcode
 *
 * Speichert den vom Client generierten Screen-Time-Passcode.
 * User setzt diesen Code manuell in iOS Settings → Screen Time.
 * Nach Cooldown abrufbar via GET /api/protection/screentime-passcode.
 *
 * Body: { passcode: string }  — 4-stelliger numerischer Code
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);

  const passcode = body?.passcode;
  if (typeof passcode !== "string" || !/^\d{4}$/.test(passcode)) {
    throw createError({ statusCode: 400, message: "passcode must be a 4-digit string" });
  }

  const db = usePrisma();
  await db.profile.update({
    where: { id: user.id },
    data: { screentimePasscode: passcode },
  });

  return { success: true };
});
