import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { createAuditLog } from '@/lib/audit';
import { errorResponse } from '@/lib/errors';
import {
  createDestination,
  listDestinations,
  type DestinationInput,
} from '@/lib/services/backup-destinations.service';
import { backupDestinationSchema } from '@/lib/validators/backup-destinations';

export const runtime = 'nodejs';

/** List configured backup destinations (secrets masked). Super-admin only. */
export const GET = withAuth(async (_req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.destinations.list');
    return NextResponse.json({ data: await listDestinations() });
  } catch (error) {
    return errorResponse(error);
  }
});

/** Create a backup destination. Super-admin only. */
export const POST = withAuth(async (req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.destinations.create');
    const body = await parseBody(req, backupDestinationSchema);
    const created = await createDestination(body as DestinationInput);
    await createAuditLog({
      userId: ctx.userId,
      portId: ctx.portId,
      action: 'create',
      entityType: 'backup_destination',
      entityId: created.id,
      severity: 'warning',
      metadata: { name: created.name, type: created.type, enabled: created.enabled },
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: created }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
});
