/**
 * GET  /api/eterra/sync-rules/global-default — Get global default frequency
 * PATCH /api/eterra/sync-rules/global-default — Set global default frequency
 */

import { prisma } from "@/core/storage/prisma";
import { NextResponse } from "next/server";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const NAMESPACE = "sync-management";
const KEY = "global-default";
const VALID_FREQUENCIES = ["3x-daily", "daily", "weekly", "monthly", "manual"];

export async function GET() {
  try {
    const row = await prisma.keyValueStore.findUnique({
      where: { namespace_key: { namespace: NAMESPACE, key: KEY } },
    });
    const val = row?.value as { frequency?: string } | null;
    return NextResponse.json({ frequency: val?.frequency ?? "monthly" });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

export async function PATCH(req: Request) {
  try {
    const body = (await req.json()) as { frequency?: string };
    if (!body.frequency || !VALID_FREQUENCIES.includes(body.frequency)) {
      return NextResponse.json({ error: "Frecventa invalida" }, { status: 400 });
    }

    await prisma.keyValueStore.upsert({
      where: { namespace_key: { namespace: NAMESPACE, key: KEY } },
      update: { value: { frequency: body.frequency } },
      create: { namespace: NAMESPACE, key: KEY, value: { frequency: body.frequency } },
    });

    return NextResponse.json({ frequency: body.frequency });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
