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 { rollbackAdminTemplate } from '@/lib/services/document-templates.service';
import { rollbackAdminTemplateSchema } from '@/lib/validators/document-templates';

/**
 * POST /api/v1/admin/templates/[templateId]/rollback
 * Rolls the template back to a previously saved version.
 * Creates a new version number (current + 1) with the restored content.
 *
 * Body: { version: number }
 */
export const POST = withAuth(
  withPermission('document_templates', 'manage', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, rollbackAdminTemplateSchema);
      const result = await rollbackAdminTemplate(
        ctx.portId,
        params.templateId!,
        body.version,
        ctx.userId,
        {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      );
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
