import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listBackupJobs, runBackup } from '@/lib/services/backup.service';

export const runtime = 'nodejs';

export const GET = withAuth(async (_req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.list');
    const jobs = await listBackupJobs();
    return NextResponse.json({ data: jobs });
  } catch (error) {
    return errorResponse(error);
  }
});

/** Trigger a fresh manual backup. Super-admin only. */
export const POST = withAuth(async (_req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.run');
    const result = await runBackup({ trigger: 'manual', triggeredBy: ctx.userId });
    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
});
