import { handleAutoVersioning } from './chunk-Z2BWJX7H.js';
import { toSlug } from './chunk-CGP4FZTH.js';
import { ruleGroupSchema } from './chunk-IQHNSFTT.js';
import { createPagePaginationSchema, paginationInfoSchema, statusQuerySchema } from './chunk-5CRPJSGU.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-D5VCL56B.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import z from 'zod';

var storedPromptBlockIdPathParams = z.object({
  storedPromptBlockId: z.string().describe("Unique identifier for the stored prompt block")
});
var storageOrderBySchema = z.object({
  field: z.enum(["createdAt", "updatedAt"]).optional(),
  direction: z.enum(["ASC", "DESC"]).optional()
});
var listStoredPromptBlocksQuerySchema = createPagePaginationSchema(100).extend({
  orderBy: storageOrderBySchema.optional(),
  status: z.enum(["draft", "published", "archived"]).optional().default("published").describe("Filter prompt blocks by status (defaults to published)"),
  authorId: z.string().optional().describe("Filter prompt blocks by author identifier"),
  metadata: z.record(z.string(), z.unknown()).optional().describe("Filter prompt blocks by metadata key-value pairs")
});
var snapshotConfigSchema = z.object({
  name: z.string().describe("Display name of the prompt block"),
  description: z.string().optional().describe("Purpose description"),
  content: z.string().describe("Template content with {{variable}} interpolation"),
  rules: ruleGroupSchema.optional().describe("Rules for conditional inclusion")
});
var createStoredPromptBlockBodySchema = z.object({
  id: z.string().optional().describe("Unique identifier. If not provided, derived from name."),
  authorId: z.string().optional().describe("Author identifier for multi-tenant filtering"),
  metadata: z.record(z.string(), z.unknown()).optional().describe("Additional metadata for the prompt block")
}).merge(snapshotConfigSchema);
var updateStoredPromptBlockBodySchema = z.object({
  authorId: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional()
}).merge(snapshotConfigSchema.partial());
var storedPromptBlockSchema = z.object({
  id: z.string(),
  status: z.string().describe("Prompt block status: draft, published, or archived"),
  activeVersionId: z.string().optional(),
  authorId: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
  createdAt: z.coerce.date(),
  updatedAt: z.coerce.date(),
  name: z.string().describe("Display name of the prompt block"),
  description: z.string().optional().describe("Purpose description"),
  content: z.string().describe("Template content with {{variable}} interpolation"),
  rules: ruleGroupSchema.optional().describe("Rules for conditional inclusion")
});
var listStoredPromptBlocksResponseSchema = paginationInfoSchema.extend({
  promptBlocks: z.array(storedPromptBlockSchema)
});
var getStoredPromptBlockResponseSchema = storedPromptBlockSchema;
var createStoredPromptBlockResponseSchema = storedPromptBlockSchema;
var updateStoredPromptBlockResponseSchema = z.union([
  z.object({
    id: z.string(),
    status: z.string(),
    activeVersionId: z.string().optional(),
    authorId: z.string().optional(),
    metadata: z.record(z.string(), z.unknown()).optional(),
    createdAt: z.coerce.date(),
    updatedAt: z.coerce.date()
  }),
  storedPromptBlockSchema
]);
var deleteStoredPromptBlockResponseSchema = z.object({
  success: z.boolean(),
  message: z.string()
});

// src/server/handlers/stored-prompt-blocks.ts
var PROMPT_BLOCK_SNAPSHOT_CONFIG_FIELDS = ["name", "description", "content", "rules"];
var LIST_STORED_PROMPT_BLOCKS_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new 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 handleError(error, "Error listing stored prompt blocks");
    }
  }
});
var GET_STORED_PROMPT_BLOCK_ROUTE = createRoute({
  method: "GET",
  path: "/stored/prompt-blocks/:storedPromptBlockId",
  responseType: "json",
  pathParamSchema: storedPromptBlockIdPathParams,
  queryParamSchema: 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const promptBlock = await promptBlockStore.getByIdResolved(storedPromptBlockId, { status });
      if (!promptBlock) {
        throw new HTTPException(404, { message: `Stored prompt block with id ${storedPromptBlockId} not found` });
      }
      return promptBlock;
    } catch (error) {
      return handleError(error, "Error getting stored prompt block");
    }
  }
});
var CREATE_STORED_PROMPT_BLOCK_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const id = providedId || toSlug(name);
      if (!id) {
        throw new 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 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 HTTPException(500, { message: "Failed to resolve created prompt block" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error creating stored prompt block");
    }
  }
});
var UPDATE_STORED_PROMPT_BLOCK_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const existing = await promptBlockStore.getById(storedPromptBlockId);
      if (!existing) {
        throw new 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 handleAutoVersioning(
        promptBlockStore,
        storedPromptBlockId,
        "blockId",
        PROMPT_BLOCK_SNAPSHOT_CONFIG_FIELDS,
        existing,
        updatedPromptBlock,
        providedConfigFields
      );
      const resolved = await promptBlockStore.getByIdResolved(storedPromptBlockId, { status: "draft" });
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve updated prompt block" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error updating stored prompt block");
    }
  }
});
var DELETE_STORED_PROMPT_BLOCK_ROUTE = 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 HTTPException(500, { message: "Storage is not configured" });
      }
      const promptBlockStore = await storage.getStore("promptBlocks");
      if (!promptBlockStore) {
        throw new HTTPException(500, { message: "Prompt blocks storage domain is not available" });
      }
      const existing = await promptBlockStore.getById(storedPromptBlockId);
      if (!existing) {
        throw new 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 handleError(error, "Error deleting stored prompt block");
    }
  }
});

export { CREATE_STORED_PROMPT_BLOCK_ROUTE, DELETE_STORED_PROMPT_BLOCK_ROUTE, GET_STORED_PROMPT_BLOCK_ROUTE, LIST_STORED_PROMPT_BLOCKS_ROUTE, UPDATE_STORED_PROMPT_BLOCK_ROUTE };
//# sourceMappingURL=chunk-DA7PQ2JQ.js.map
//# sourceMappingURL=chunk-DA7PQ2JQ.js.map