'use strict';

var chunkKD3YOO6V_cjs = require('./chunk-KD3YOO6V.cjs');
var chunkAWQJBTJ4_cjs = require('./chunk-AWQJBTJ4.cjs');
var chunkA7CIMRJQ_cjs = require('./chunk-A7CIMRJQ.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunk4LVJBXI2_cjs = require('./chunk-4LVJBXI2.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var z = require('zod');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var z__default = /*#__PURE__*/_interopDefault(z);

var listPromptBlockVersionsQuerySchema = chunkKD3YOO6V_cjs.listVersionsQuerySchema;
var comparePromptBlockVersionsQuerySchema = chunkKD3YOO6V_cjs.compareVersionsQuerySchema;
var createPromptBlockVersionBodySchema = chunkKD3YOO6V_cjs.createVersionBodySchema;
var promptBlockVersionPathParams = z__default.default.object({
  promptBlockId: z__default.default.string().describe("Unique identifier for the stored prompt block")
});
var promptBlockVersionIdPathParams = z__default.default.object({
  promptBlockId: z__default.default.string().describe("Unique identifier for the stored prompt block"),
  versionId: z__default.default.string().describe("Unique identifier for the version (UUID)")
});
var promptBlockVersionSchema = z__default.default.object({
  id: z__default.default.string().describe("Unique identifier for the version (UUID)"),
  blockId: z__default.default.string().describe("ID of the prompt block this version belongs to"),
  versionNumber: z__default.default.number().describe("Sequential version number (1, 2, 3, ...)"),
  // Snapshot config fields
  name: z__default.default.string().describe("Display name of the prompt block"),
  description: z__default.default.string().optional().describe("Purpose description"),
  content: z__default.default.string().describe("Template content with {{variable}} interpolation"),
  rules: chunkA7CIMRJQ_cjs.ruleGroupSchema.optional().describe("Rules for conditional inclusion"),
  // Version metadata
  changedFields: z__default.default.array(z__default.default.string()).optional().describe("Array of field names that changed from the previous version"),
  changeMessage: z__default.default.string().optional().describe("Optional message describing the changes"),
  createdAt: z__default.default.coerce.date().describe("When this version was created")
});
var listPromptBlockVersionsResponseSchema = chunkKD3YOO6V_cjs.createListVersionsResponseSchema(promptBlockVersionSchema);
var getPromptBlockVersionResponseSchema = promptBlockVersionSchema;
var createPromptBlockVersionResponseSchema = promptBlockVersionSchema.partial().merge(
  z__default.default.object({
    id: z__default.default.string(),
    blockId: z__default.default.string(),
    versionNumber: z__default.default.number(),
    createdAt: z__default.default.coerce.date()
  })
);
var activatePromptBlockVersionResponseSchema = chunkKD3YOO6V_cjs.activateVersionResponseSchema;
var restorePromptBlockVersionResponseSchema = promptBlockVersionSchema;
var deletePromptBlockVersionResponseSchema = chunkKD3YOO6V_cjs.deleteVersionResponseSchema;
var comparePromptBlockVersionsResponseSchema = chunkKD3YOO6V_cjs.createCompareVersionsResponseSchema(promptBlockVersionSchema);

// src/server/handlers/prompt-block-versions.ts
var SNAPSHOT_CONFIG_FIELDS = ["name", "description", "content", "rules"];
var LIST_PROMPT_BLOCK_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/prompt-blocks/:promptBlockId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: promptBlockVersionPathParams,
  queryParamSchema: listPromptBlockVersionsQuerySchema,
  responseSchema: listPromptBlockVersionsResponseSchema,
  summary: "List prompt block versions",
  description: "Returns a paginated list of all versions for a stored prompt block",
  tags: ["Prompt Block Versions"],
  handler: async ({ mastra, promptBlockId, page, perPage, orderBy }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const promptBlock = await promptBlockStore.getById(promptBlockId);
      if (!promptBlock) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Prompt block with id ${promptBlockId} not found` });
      }
      const result = await promptBlockStore.listVersions({
        blockId: promptBlockId,
        page,
        perPage,
        orderBy
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing prompt block versions");
    }
  }
});
var CREATE_PROMPT_BLOCK_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/prompt-blocks/:promptBlockId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: promptBlockVersionPathParams,
  bodySchema: createPromptBlockVersionBodySchema,
  responseSchema: createPromptBlockVersionResponseSchema,
  summary: "Create prompt block version",
  description: "Creates a new version snapshot of the current prompt block configuration",
  tags: ["Prompt Block Versions"],
  handler: async ({ mastra, promptBlockId, changeMessage }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const promptBlock = await promptBlockStore.getById(promptBlockId);
      if (!promptBlock) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Prompt block with id ${promptBlockId} not found` });
      }
      let currentConfig = {};
      if (promptBlock.activeVersionId) {
        const activeVersion = await promptBlockStore.getVersion(promptBlock.activeVersionId);
        if (activeVersion) {
          currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
            activeVersion,
            SNAPSHOT_CONFIG_FIELDS
          );
        }
      }
      const latestVersion = await promptBlockStore.getLatestVersion(promptBlockId);
      if (!promptBlock.activeVersionId && latestVersion) {
        currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
          latestVersion,
          SNAPSHOT_CONFIG_FIELDS
        );
      }
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, currentConfig);
      const { versionId } = await chunkAWQJBTJ4_cjs.createVersionWithRetry(
        promptBlockStore,
        promptBlockId,
        "blockId",
        currentConfig,
        changedFields,
        { changeMessage }
      );
      const version = await promptBlockStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        promptBlockStore,
        promptBlockId,
        "blockId",
        promptBlock.activeVersionId
      );
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating prompt block version");
    }
  }
});
var GET_PROMPT_BLOCK_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/prompt-blocks/:promptBlockId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: promptBlockVersionIdPathParams,
  responseSchema: getPromptBlockVersionResponseSchema,
  summary: "Get prompt block version",
  description: "Returns a specific version of a prompt block by its version ID",
  tags: ["Prompt Block Versions"],
  handler: async ({ mastra, promptBlockId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const version = await promptBlockStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.blockId !== promptBlockId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for prompt block ${promptBlockId}`
        });
      }
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting prompt block version");
    }
  }
});
var ACTIVATE_PROMPT_BLOCK_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/prompt-blocks/:promptBlockId/versions/:versionId/activate",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: promptBlockVersionIdPathParams,
  responseSchema: activatePromptBlockVersionResponseSchema,
  summary: "Activate prompt block version",
  description: "Sets a specific version as the active version for the prompt block",
  tags: ["Prompt Block Versions"],
  handler: async ({ mastra, promptBlockId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const promptBlock = await promptBlockStore.getById(promptBlockId);
      if (!promptBlock) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Prompt block with id ${promptBlockId} not found` });
      }
      const version = await promptBlockStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.blockId !== promptBlockId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for prompt block ${promptBlockId}`
        });
      }
      await promptBlockStore.update({
        id: promptBlockId,
        activeVersionId: versionId,
        status: "published"
      });
      mastra.getEditor()?.prompt.clearCache(promptBlockId);
      return {
        success: true,
        message: `Version ${version.versionNumber} is now active`,
        activeVersionId: versionId
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error activating prompt block version");
    }
  }
});
var RESTORE_PROMPT_BLOCK_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/prompt-blocks/:promptBlockId/versions/:versionId/restore",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: promptBlockVersionIdPathParams,
  responseSchema: restorePromptBlockVersionResponseSchema,
  summary: "Restore prompt block version",
  description: "Restores the prompt block configuration from a version, creating a new version",
  tags: ["Prompt Block Versions"],
  handler: async ({ mastra, promptBlockId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const promptBlock = await promptBlockStore.getById(promptBlockId);
      if (!promptBlock) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Prompt block with id ${promptBlockId} not found` });
      }
      const versionToRestore = await promptBlockStore.getVersion(versionId);
      if (!versionToRestore) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (versionToRestore.blockId !== promptBlockId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for prompt block ${promptBlockId}`
        });
      }
      const restoredConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        versionToRestore,
        SNAPSHOT_CONFIG_FIELDS
      );
      await promptBlockStore.update({
        id: promptBlockId,
        ...restoredConfig
      });
      const latestVersion = await promptBlockStore.getLatestVersion(promptBlockId);
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(latestVersion, SNAPSHOT_CONFIG_FIELDS) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, restoredConfig);
      const { versionId: newVersionId } = await chunkAWQJBTJ4_cjs.createVersionWithRetry(
        promptBlockStore,
        promptBlockId,
        "blockId",
        restoredConfig,
        changedFields,
        {
          changeMessage: `Restored from version ${versionToRestore.versionNumber}`
        }
      );
      const newVersion = await promptBlockStore.getVersion(newVersionId);
      if (!newVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        promptBlockStore,
        promptBlockId,
        "blockId",
        promptBlock.activeVersionId
      );
      mastra.getEditor()?.prompt.clearCache(promptBlockId);
      return newVersion;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error restoring prompt block version");
    }
  }
});
var DELETE_PROMPT_BLOCK_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "DELETE",
  path: "/stored/prompt-blocks/:promptBlockId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: promptBlockVersionIdPathParams,
  responseSchema: deletePromptBlockVersionResponseSchema,
  summary: "Delete prompt block version",
  description: "Deletes a specific version (cannot delete the active version)",
  tags: ["Prompt Block Versions"],
  handler: async ({ mastra, promptBlockId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const promptBlock = await promptBlockStore.getById(promptBlockId);
      if (!promptBlock) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Prompt block with id ${promptBlockId} not found` });
      }
      const version = await promptBlockStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.blockId !== promptBlockId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for prompt block ${promptBlockId}`
        });
      }
      if (promptBlock.activeVersionId === versionId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Cannot delete the active version. Activate a different version first."
        });
      }
      await promptBlockStore.deleteVersion(versionId);
      mastra.getEditor()?.prompt.clearCache(promptBlockId);
      return {
        success: true,
        message: `Version ${version.versionNumber} deleted successfully`
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error deleting prompt block version");
    }
  }
});
var COMPARE_PROMPT_BLOCK_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/prompt-blocks/:promptBlockId/versions/compare",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: promptBlockVersionPathParams,
  queryParamSchema: comparePromptBlockVersionsQuerySchema,
  responseSchema: comparePromptBlockVersionsResponseSchema,
  summary: "Compare prompt block versions",
  description: "Compares two versions and returns the differences between them",
  tags: ["Prompt Block Versions"],
  handler: async ({ mastra, promptBlockId, from, to }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const fromVersion = await promptBlockStore.getVersion(from);
      if (!fromVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${from} not found` });
      }
      if (fromVersion.blockId !== promptBlockId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${from} not found for prompt block ${promptBlockId}`
        });
      }
      const toVersion = await promptBlockStore.getVersion(to);
      if (!toVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${to} not found` });
      }
      if (toVersion.blockId !== promptBlockId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${to} not found for prompt block ${promptBlockId}`
        });
      }
      const fromConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        fromVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const toConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        toVersion,
        SNAPSHOT_CONFIG_FIELDS
      );
      const diffs = chunkAWQJBTJ4_cjs.computeVersionDiffs(fromConfig, toConfig);
      return {
        diffs,
        fromVersion,
        toVersion
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error comparing prompt block versions");
    }
  }
});

exports.ACTIVATE_PROMPT_BLOCK_VERSION_ROUTE = ACTIVATE_PROMPT_BLOCK_VERSION_ROUTE;
exports.COMPARE_PROMPT_BLOCK_VERSIONS_ROUTE = COMPARE_PROMPT_BLOCK_VERSIONS_ROUTE;
exports.CREATE_PROMPT_BLOCK_VERSION_ROUTE = CREATE_PROMPT_BLOCK_VERSION_ROUTE;
exports.DELETE_PROMPT_BLOCK_VERSION_ROUTE = DELETE_PROMPT_BLOCK_VERSION_ROUTE;
exports.GET_PROMPT_BLOCK_VERSION_ROUTE = GET_PROMPT_BLOCK_VERSION_ROUTE;
exports.LIST_PROMPT_BLOCK_VERSIONS_ROUTE = LIST_PROMPT_BLOCK_VERSIONS_ROUTE;
exports.RESTORE_PROMPT_BLOCK_VERSION_ROUTE = RESTORE_PROMPT_BLOCK_VERSION_ROUTE;
//# sourceMappingURL=chunk-FOX2GBIB.cjs.map
//# sourceMappingURL=chunk-FOX2GBIB.cjs.map