import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listAdminTemplates, createAdminTemplate } from '@/lib/services/document-templates.service';
import {
  listAdminTemplatesSchema,
  createAdminTemplateSchema,
} from '@/lib/validators/document-templates';

/**
 * GET /api/v1/admin/templates
 * List TipTap-based document templates for the port.
 */
export const GET = withAuth(
  withPermission('document_templates', 'manage', async (req, ctx) => {
    try {
      const query = parseQuery(req, listAdminTemplatesSchema);
      const data = await listAdminTemplates(ctx.portId, query);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

/**
 * POST /api/v1/admin/templates
 * Create a new TipTap-based document template.
 */
export const POST = withAuth(
  withPermission('document_templates', 'manage', async (req, ctx) => {
    try {
      const body = await parseBody(req, createAdminTemplateSchema);
      const template = await createAdminTemplate(ctx.portId, ctx.userId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: template }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
