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 {
  getAdminTemplate,
  updateAdminTemplate,
  deleteAdminTemplate,
} from '@/lib/services/document-templates.service';
import { updateAdminTemplateSchema } from '@/lib/validators/document-templates';

/**
 * GET /api/v1/admin/templates/[templateId]
 * Retrieve a single TipTap-based document template.
 */
export const GET = withAuth(
  withPermission('document_templates', 'manage', async (req, ctx, params) => {
    try {
      const template = await getAdminTemplate(ctx.portId, params.templateId!);
      return NextResponse.json({ data: template });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

/**
 * PATCH /api/v1/admin/templates/[templateId]
 * Update a TipTap-based document template. Increments version if content changes.
 */
export const PATCH = withAuth(
  withPermission('document_templates', 'manage', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, updateAdminTemplateSchema);
      const updated = await updateAdminTemplate(ctx.portId, params.templateId!, ctx.userId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: updated });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

/**
 * DELETE /api/v1/admin/templates/[templateId]
 * Delete a TipTap-based document template.
 */
export const DELETE = withAuth(
  withPermission('document_templates', 'manage', async (req, ctx, params) => {
    try {
      await deleteAdminTemplate(ctx.portId, params.templateId!, ctx.userId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
