import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { listSettings, upsertSetting, deleteSetting } from '@/lib/services/settings.service';
import { upsertSettingSchema, deleteSettingSchema } from '@/lib/validators/settings';
import { errorResponse } from '@/lib/errors';

export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      const data = await listSettings(ctx.portId);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PUT = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const { key, value } = await parseBody(req, upsertSettingSchema);
      const data = await upsertSetting(key, value, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const { key } = await parseBody(req, deleteSettingSchema);
      await deleteSetting(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);
    }
  }),
);
