import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { writeSetting, deleteSetting } from '@/lib/settings/resolver';

const putSchema = z.object({
  value: z.unknown(),
});

/**
 * PUT /api/v1/admin/settings/:key
 *
 * Writes a registry-known setting. The resolver validates against the
 * entry's Zod schema, encrypts at rest if registered as such, and writes
 * an audit log with secrets masked.
 *
 * Body: { value: <whatever the entry's type accepts> }
 *
 * Empty / null `value` on a non-sensitive field DELETEs the row (reverts
 * to global → env → default). On a sensitive/encrypted field, empty is a
 * no-op so an unchanged save through the ••• placeholder doesn't wipe
 * the stored ciphertext. Use the DELETE endpoint to explicitly revert.
 */
export const PUT = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx, params) => {
    try {
      const { value } = await parseBody(req, putSchema);
      await writeSetting(params.key!, value, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

/**
 * DELETE /api/v1/admin/settings/:key
 *
 * Removes the row, reverting the resolver to global → env → default.
 * 404 if no row exists at the appropriate scope.
 */
export const DELETE = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
    try {
      await deleteSetting(params.key!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
