import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, NotFoundError } from '@/lib/errors';
import {
  deleteFormTemplate,
  getFormTemplateById,
  updateFormTemplate,
} from '@/lib/services/form-templates.service';
import { updateFormTemplateSchema } from '@/lib/validators/form-templates';

export const GET = withAuth(
  withPermission('admin', 'manage_forms', async (_req, ctx, params) => {
    try {
      if (!params.id) throw new NotFoundError('Form template');
      const tpl = await getFormTemplateById(params.id, ctx.portId);
      return NextResponse.json({ data: tpl });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PATCH = withAuth(
  withPermission('admin', 'manage_forms', async (req, ctx, params) => {
    try {
      if (!params.id) throw new NotFoundError('Form template');
      const body = await parseBody(req, updateFormTemplateSchema);
      const tpl = await updateFormTemplate(params.id, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: tpl });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('admin', 'manage_forms', async (_req, ctx, params) => {
    try {
      if (!params.id) throw new NotFoundError('Form template');
      await deleteFormTemplate(params.id, 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);
    }
  }),
);
