import { NextResponse } from 'next/server';

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

export const runtime = 'nodejs';

/**
 * Test connectivity to a destination (connect + verify the target dir/bucket).
 * Returns `{ data: { ok: true } }` or a structured error the UI can surface.
 * Super-admin only.
 */
export const POST = withAuth(async (_req, ctx, params) => {
  try {
    requireSuperAdmin(ctx, 'admin.backup.destinations.test');
    const id = params.id;
    if (!id) throw new NotFoundError('Backup destination');
    await testDestination(id);
    return NextResponse.json({ data: { ok: true } });
  } catch (error) {
    return errorResponse(error);
  }
});
