/**
 * POST /api/eterra/sync-rules/bulk — Bulk operations on sync rules
 *
 * Actions:
 * - set-county-frequency: Create or update a county-level rule
 * - enable/disable: Toggle multiple rules by IDs
 * - delete: Delete multiple rules by IDs
 */

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;
}

type BulkBody = {
  action: string;
  county?: string;
  frequency?: string;
  syncEnrich?: boolean;
  syncNoGeom?: boolean;
  ruleIds?: string[];
};

export async function POST(req: Request) {
  try {
    const body = (await req.json()) as BulkBody;

    switch (body.action) {
      case "set-county-frequency": {
        if (!body.county || !body.frequency) {
          return NextResponse.json({ error: "county si frequency obligatorii" }, { status: 400 });
        }
        if (!VALID_FREQUENCIES.includes(body.frequency)) {
          return NextResponse.json({ error: "Frecventa invalida" }, { status: 400 });
        }

        // Upsert county-level rule
        const existing = await prisma.gisSyncRule.findFirst({
          where: { county: body.county, siruta: null },
        });

        const rule = existing
          ? await prisma.gisSyncRule.update({
              where: { id: existing.id },
              data: {
                frequency: body.frequency,
                syncEnrich: body.syncEnrich ?? existing.syncEnrich,
                syncNoGeom: body.syncNoGeom ?? existing.syncNoGeom,
                nextDueAt: computeNextDue(body.frequency, existing.lastSyncAt),
              },
            })
          : await prisma.gisSyncRule.create({
              data: {
                county: body.county,
                frequency: body.frequency,
                syncEnrich: body.syncEnrich ?? false,
                syncNoGeom: body.syncNoGeom ?? false,
                nextDueAt: computeNextDue(body.frequency, null),
              },
            });

        return NextResponse.json({ rule, action: "set-county-frequency" });
      }

      case "enable":
      case "disable": {
        if (!body.ruleIds?.length) {
          return NextResponse.json({ error: "ruleIds obligatorii" }, { status: 400 });
        }
        const result = await prisma.gisSyncRule.updateMany({
          where: { id: { in: body.ruleIds } },
          data: { enabled: body.action === "enable" },
        });
        return NextResponse.json({ updated: result.count, action: body.action });
      }

      case "delete": {
        if (!body.ruleIds?.length) {
          return NextResponse.json({ error: "ruleIds obligatorii" }, { status: 400 });
        }
        const result = await prisma.gisSyncRule.deleteMany({
          where: { id: { in: body.ruleIds } },
        });
        return NextResponse.json({ deleted: result.count, action: "delete" });
      }

      default:
        return NextResponse.json({ error: `Actiune necunoscuta: ${body.action}` }, { status: 400 });
    }
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Eroare server";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
