'use strict';

var chunkAWQJBTJ4_cjs = require('./chunk-AWQJBTJ4.cjs');
var chunkJ5IJWZEA_cjs = require('./chunk-J5IJWZEA.cjs');
var chunkA7CIMRJQ_cjs = require('./chunk-A7CIMRJQ.cjs');
var chunkRWLJZWDL_cjs = require('./chunk-RWLJZWDL.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 storedPromptBlockIdPathParams = z__default.default.object({
  storedPromptBlockId: z__default.default.string().describe("Unique identifier for the stored prompt block")
});
var storageOrderBySchema = z__default.default.object({
  field: z__default.default.enum(["createdAt", "updatedAt"]).optional(),
  direction: z__default.default.enum(["ASC", "DESC"]).optional()
});
var listStoredPromptBlocksQuerySchema = chunkRWLJZWDL_cjs.createPagePaginationSchema(100).extend({
  orderBy: storageOrderBySchema.optional(),
  status: z__default.default.enum(["draft", "published", "archived"]).optional().default("published").describe("Filter prompt blocks by status (defaults to published)"),
  authorId: z__default.default.string().optional().describe("Filter prompt blocks by author identifier"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Filter prompt blocks by metadata key-value pairs")
});
var snapshotConfigSchema = z__default.default.object({
  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")
});
var createStoredPromptBlockBodySchema = z__default.default.object({
  id: z__default.default.string().optional().describe("Unique identifier. If not provided, derived from name."),
  authorId: z__default.default.string().optional().describe("Author identifier for multi-tenant filtering"),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional().describe("Additional metadata for the prompt block")
}).merge(snapshotConfigSchema);
var updateStoredPromptBlockBodySchema = z__default.default.object({
  authorId: z__default.default.string().optional(),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional()
}).merge(snapshotConfigSchema.partial());
var storedPromptBlockSchema = z__default.default.object({
  id: z__default.default.string(),
  status: z__default.default.string().describe("Prompt block status: draft, published, or archived"),
  activeVersionId: z__default.default.string().optional(),
  authorId: z__default.default.string().optional(),
  metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional(),
  createdAt: z__default.default.coerce.date(),
  updatedAt: z__default.default.coerce.date(),
  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")
});
var listStoredPromptBlocksResponseSchema = chunkRWLJZWDL_cjs.paginationInfoSchema.extend({
  promptBlocks: z__default.default.array(storedPromptBlockSchema)
});
var getStoredPromptBlockResponseSchema = storedPromptBlockSchema;
var createStoredPromptBlockResponseSchema = storedPromptBlockSchema;
var updateStoredPromptBlockResponseSchema = z__default.default.union([
  z__default.default.object({
    id: z__default.default.string(),
    status: z__default.default.string(),
    activeVersionId: z__default.default.string().optional(),
    authorId: z__default.default.string().optional(),
    metadata: z__default.default.record(z__default.default.string(), z__default.default.unknown()).optional(),
    createdAt: z__default.default.coerce.date(),
    updatedAt: z__default.default.coerce.date()
  }),
  storedPromptBlockSchema
]);
var deleteStoredPromptBlockResponseSchema = z__default.default.object({
  success: z__default.default.boolean(),
  message: z__default.default.string()
});

// src/server/handlers/stored-prompt-blocks.ts
var PROMPT_BLOCK_SNAPSHOT_CONFIG_FIELDS = ["name", "description", "content", "rules"];
var LIST_STORED_PROMPT_BLOCKS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/prompt-blocks",
  responseType: "json",
  queryParamSchema: listStoredPromptBlocksQuerySchema,
  responseSchema: listStoredPromptBlocksResponseSchema,
  summary: "List stored prompt blocks",
  description: "Returns a paginated list of all prompt blocks stored in the database",
  tags: ["Stored Prompt Blocks"],
  requiresAuth: true,
  handler: async ({ mastra, page, perPage, orderBy, status, authorId, metadata }) => {
    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 result = await promptBlockStore.listResolved({
        page,
        perPage,
        orderBy,
        status,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing stored prompt blocks");
    }
  }
});
var GET_STORED_PROMPT_BLOCK_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/prompt-blocks/:storedPromptBlockId",
  responseType: "json",
  pathParamSchema: storedPromptBlockIdPathParams,
  queryParamSchema: chunkRWLJZWDL_cjs.statusQuerySchema,
  responseSchema: getStoredPromptBlockResponseSchema,
  summary: "Get stored prompt block by ID",
  description: "Returns a specific prompt block from storage by its unique identifier. Use ?status=draft to resolve with the latest (draft) version, or ?status=published (default) for the active published version.",
  tags: ["Stored Prompt Blocks"],
  requiresAuth: true,
  handler: async ({ mastra, storedPromptBlockId, status }) => {
    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.getByIdResolved(storedPromptBlockId, { status });
      if (!promptBlock) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored prompt block with id ${storedPromptBlockId} not found` });
      }
      return promptBlock;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting stored prompt block");
    }
  }
});
var CREATE_STORED_PROMPT_BLOCK_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/prompt-blocks",
  responseType: "json",
  bodySchema: createStoredPromptBlockBodySchema,
  responseSchema: createStoredPromptBlockResponseSchema,
  summary: "Create stored prompt block",
  description: "Creates a new prompt block in storage with the provided configuration",
  tags: ["Stored Prompt Blocks"],
  requiresAuth: true,
  handler: async ({ mastra, id: providedId, authorId, metadata, name, description, content, rules }) => {
    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 id = providedId || chunkJ5IJWZEA_cjs.toSlug(name);
      if (!id) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Could not derive prompt block ID from name. Please provide an explicit id."
        });
      }
      const existing = await promptBlockStore.getById(id);
      if (existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(409, { message: `Prompt block with id ${id} already exists` });
      }
      await promptBlockStore.create({
        promptBlock: {
          id,
          authorId,
          metadata,
          name,
          description,
          content,
          rules
        }
      });
      const resolved = await promptBlockStore.getByIdResolved(id, { status: "draft" });
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created prompt block" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating stored prompt block");
    }
  }
});
var UPDATE_STORED_PROMPT_BLOCK_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "PATCH",
  path: "/stored/prompt-blocks/:storedPromptBlockId",
  responseType: "json",
  pathParamSchema: storedPromptBlockIdPathParams,
  bodySchema: updateStoredPromptBlockBodySchema,
  responseSchema: updateStoredPromptBlockResponseSchema,
  summary: "Update stored prompt block",
  description: "Updates an existing prompt block in storage with the provided fields",
  tags: ["Stored Prompt Blocks"],
  requiresAuth: true,
  handler: async ({
    mastra,
    storedPromptBlockId,
    // Metadata-level fields
    authorId,
    metadata,
    // Config fields (snapshot-level)
    name,
    description,
    content,
    rules
  }) => {
    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 existing = await promptBlockStore.getById(storedPromptBlockId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored prompt block with id ${storedPromptBlockId} not found` });
      }
      const updatedPromptBlock = await promptBlockStore.update({
        id: storedPromptBlockId,
        authorId,
        metadata,
        name,
        description,
        content,
        rules
      });
      const configFields = { name, description, content, rules };
      const providedConfigFields = Object.fromEntries(Object.entries(configFields).filter(([_, v]) => v !== void 0));
      await chunkAWQJBTJ4_cjs.handleAutoVersioning(
        promptBlockStore,
        storedPromptBlockId,
        "blockId",
        PROMPT_BLOCK_SNAPSHOT_CONFIG_FIELDS,
        existing,
        updatedPromptBlock,
        providedConfigFields
      );
      const resolved = await promptBlockStore.getByIdResolved(storedPromptBlockId, { status: "draft" });
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated prompt block" });
      }
      return resolved;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error updating stored prompt block");
    }
  }
});
var DELETE_STORED_PROMPT_BLOCK_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "DELETE",
  path: "/stored/prompt-blocks/:storedPromptBlockId",
  responseType: "json",
  pathParamSchema: storedPromptBlockIdPathParams,
  responseSchema: deleteStoredPromptBlockResponseSchema,
  summary: "Delete stored prompt block",
  description: "Deletes a prompt block from storage by its unique identifier",
  tags: ["Stored Prompt Blocks"],
  requiresAuth: true,
  handler: async ({ mastra, storedPromptBlockId }) => {
    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 existing = await promptBlockStore.getById(storedPromptBlockId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored prompt block with id ${storedPromptBlockId} not found` });
      }
      await promptBlockStore.delete(storedPromptBlockId);
      return {
        success: true,
        message: `Prompt block ${storedPromptBlockId} deleted successfully`
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error deleting stored prompt block");
    }
  }
});

exports.CREATE_STORED_PROMPT_BLOCK_ROUTE = CREATE_STORED_PROMPT_BLOCK_ROUTE;
exports.DELETE_STORED_PROMPT_BLOCK_ROUTE = DELETE_STORED_PROMPT_BLOCK_ROUTE;
exports.GET_STORED_PROMPT_BLOCK_ROUTE = GET_STORED_PROMPT_BLOCK_ROUTE;
exports.LIST_STORED_PROMPT_BLOCKS_ROUTE = LIST_STORED_PROMPT_BLOCKS_ROUTE;
exports.UPDATE_STORED_PROMPT_BLOCK_ROUTE = UPDATE_STORED_PROMPT_BLOCK_ROUTE;
//# sourceMappingURL=chunk-6B2LGUBB.cjs.map
//# sourceMappingURL=chunk-6B2LGUBB.cjs.map