import { NextResponse } from 'next/server';
import { stat } from 'node:fs/promises';
import path from 'node:path';
import { checkSystemBin } from '@/lib/system-bins';
import { restoreFromZipFile } from '@/lib/restore-zip';

export const dynamic = 'force-dynamic';
export const maxDuration = 600;

const PRESET_PATH = path.join(process.cwd(), 'factory', 'preset.zip');

export async function POST() {
  if (!(await checkSystemBin('unzip', '-v'))) {
    return NextResponse.json({ error: "Binario 'unzip' non disponibile sul server." }, { status: 503 });
  }

  try {
    await stat(PRESET_PATH);
  } catch {
    return NextResponse.json(
      { error: 'Nessun factory preset configurato. Imposta prima lo stato attuale come preset.' },
      { status: 404 },
    );
  }

  const result = await restoreFromZipFile(PRESET_PATH);
  if (!result.ok) {
    return NextResponse.json({ error: result.error, detail: result.detail }, { status: result.status });
  }
  return NextResponse.json({
    ok: true,
    restored: { cards: result.cards, portals: result.portals },
    previousDataBackup: result.previousBackup,
  });
}
