/**
 * PATCH  /api/eterra/sync-rules/[id] — Update a sync rule
 * DELETE /api/eterra/sync-rules/[id] — Delete a sync rule
 */

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

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

const VALID_FREQUENCIES = ["3x-daily", "daily", "weekly", "monthly", "manual"];

function computeNextDue(frequency: string, lastSyncAt: Date | null): Date | null {
  if (frequency === "manual") return null;
  const base = lastSyncAt ?? new Date();
  const ms: Record<string, number> = {
    "3x-daily": 8 * 3600_000,
    daily: 24 * 3600_000,
    weekly: 7 * 24 * 3600_000,
    monthly: 30 * 24 * 3600_000,
  };
  return ms[frequency] ? new Date(base.getTime() + ms[frequency]!) : null;
}

export async function PATCH(
  req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;

  try {
    const existing = await prisma.gisSyncRule.findUnique({ where: { id } });
    if (!existing) {
      return NextResponse.json({ error: "Regula nu exista" }, { status: 404 });
    }

    const body = (await req.json()) as Record<string, unknown>;

    // Validate frequency if provided
    if (body.frequency && !VALID_FREQUENCIES.includes(body.frequency as string)) {
      return NextResponse.json({ error: "Frecventa invalida" }, { status: 400 });
    }

    // Build update data — only include provided fields
    const data: Record<string, unknown> = {};
    const fields = [
      "frequency", "syncTerenuri", "syncCladiri", "syncNoGeom", "syncEnrich",
      "priority", "enabled", "allowedHoursStart", "allowedHoursEnd",
      "allowedDays", "label",
    ];
    for (const f of fields) {
      if (f in body) data[f] = body[f];
    }

    // Recompute nextDueAt if frequency changed
    if (body.frequency) {
      data.nextDueAt = computeNextDue(
        body.frequency as string,
        existing.lastSyncAt,
      );
    }

    // If enabled changed to true and no nextDueAt, compute it
    if (body.enabled === true && !existing.nextDueAt && !data.nextDueAt) {
      const freq = (body.frequency as string) ?? existing.frequency;
      data.nextDueAt = computeNextDue(freq, existing.lastSyncAt);
    }

    const updated = await prisma.gisSyncRule.update({
      where: { id },
      data,
    });

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

export async function DELETE(
  _req: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;

  try {
    await prisma.gisSyncRule.delete({ where: { id } });
    return NextResponse.json({ ok: true });
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
