import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth } from '@/lib/api/helpers';
import { createAuditLog } from '@/lib/audit';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { pushBackupToDestination } from '@/lib/services/backup-destinations.service';

export const runtime = 'nodejs';
// A full backup (pg_dump + every blob) is assembled before the push, so allow
// a long run on large datasets.
export const maxDuration = 3600;

/** Assemble a fresh full backup and push it to this destination now. Super-admin. */
export const POST = withAuth(async (_req, ctx, params) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.destinations.run');
    const id = params.id;
    if (!id) throw new NotFoundError('Backup destination');
    const result = await pushBackupToDestination(id, {
      trigger: 'manual',
      triggeredBy: ctx.userId,
    });
    await createAuditLog({
      userId: ctx.userId,
      portId: ctx.portId,
      action: 'backup_export',
      entityType: 'backup_destination',
      entityId: id,
      severity: 'warning',
      metadata: { bytes: result.bytes, remoteRef: result.remoteRef },
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
});
