import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { copyFromEnv } from '@/lib/settings/resolver';

/**
 * POST /api/v1/admin/settings/:key/copy-from-env
 *
 * One-click migration helper used by the admin form's "Copy from env"
 * button. Reads the env var named in the registry entry's `envFallback`
 * field and writes it as the current scope's row. Returns `{ copied: false }`
 * if the env var is unset / empty.
 */
export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
    try {
      const result = await copyFromEnv(params.key!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
