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, NotFoundError } from '@/lib/errors';
import {
  deleteDestination,
  updateDestination,
  type DestinationInput,
} from '@/lib/services/backup-destinations.service';
import { backupDestinationSchema } from '@/lib/validators/backup-destinations';

export const runtime = 'nodejs';

/** Update a backup destination. Super-admin only. */
export const PUT = withAuth(async (req, ctx, params) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.destinations.update');
    const id = params.id;
    if (!id) throw new NotFoundError('Backup destination');
    const body = await parseBody(req, backupDestinationSchema);
    const updated = await updateDestination(id, body as DestinationInput);
    await createAuditLog({
      userId: ctx.userId,
      portId: ctx.portId,
      action: 'update',
      entityType: 'backup_destination',
      entityId: id,
      severity: 'warning',
      metadata: { name: updated.name, type: updated.type, enabled: updated.enabled },
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: updated });
  } catch (error) {
    return errorResponse(error);
  }
});

/** Delete a backup destination. Super-admin only. */
export const DELETE = withAuth(async (_req, ctx, params) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.destinations.delete');
    const id = params.id;
    if (!id) throw new NotFoundError('Backup destination');
    await deleteDestination(id);
    await createAuditLog({
      userId: ctx.userId,
      portId: ctx.portId,
      action: 'delete',
      entityType: 'backup_destination',
      entityId: id,
      severity: 'warning',
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return new NextResponse(null, { status: 204 });
  } catch (error) {
    return errorResponse(error);
  }
});
