import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { archiveBrochure, getBrochure, updateBrochure } from '@/lib/services/brochures.service';
import { updateBrochureSchema } from '@/lib/validators/brochures';

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

export const PATCH = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx, params) => {
    try {
      const id = params.id!;
      const input = await parseBody(req, updateBrochureSchema);
      const data = await updateBrochure(ctx.portId, id, input);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
    try {
      const id = params.id!;
      await archiveBrochure(ctx.portId, id);
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
