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 { createBrochure, listBrochures } from '@/lib/services/brochures.service';
import { createBrochureSchema } from '@/lib/validators/brochures';

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

export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const input = await parseBody(req, createBrochureSchema);
      const data = await createBrochure({
        portId: ctx.portId,
        label: input.label,
        description: input.description ?? null,
        isDefault: input.isDefault,
        createdBy: ctx.userId,
      });
      return NextResponse.json({ data }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
