import { listStoredPromptBlocksResponseSchema, listStoredPromptBlocksQuerySchema, getStoredPromptBlockResponseSchema, storedPromptBlockIdPathParams, createStoredPromptBlockResponseSchema, createStoredPromptBlockBodySchema, updateStoredPromptBlockResponseSchema, updateStoredPromptBlockBodySchema, deleteStoredPromptBlockResponseSchema } from './chunk-7NDOPT3W.js';
import { handleAutoVersioning } from './chunk-33QPJPK4.js';
import { toSlug } from './chunk-2E5ZB7FH.js';
import { statusQuerySchema } from './chunk-USZD5AX2.js';
import { handleError } from './chunk-NA7LKQPZ.js';
import { createRoute } from './chunk-OLKVMPNB.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';

// src/server/handlers/stored-prompt-blocks.ts
var PROMPT_BLOCK_SNAPSHOT_CONFIG_FIELDS = [
  "name",
  "description",
  "content",
  "rules",
  "requestContextSchema"
];
function computeHasDraft(latestVersion, activeVersionId) {
  return !!(latestVersion && (!activeVersionId || latestVersion.id !== activeVersionId));
}
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
      });
      const promptBlocks = await Promise.all(
        result.promptBlocks.map(async (block) => {
          const latestVersion = await promptBlockStore.getLatestVersion(block.id);
          return { ...block, hasDraft: computeHasDraft(latestVersion, block.activeVersionId) };
        })
      );
      return { ...result, promptBlocks };
    } 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` });
      }
      const latestVersion = await promptBlockStore.getLatestVersion(storedPromptBlockId);
      return { ...promptBlock, hasDraft: computeHasDraft(latestVersion, promptBlock.activeVersionId) };
    } 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,
    requestContextSchema
  }) => {
    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,
          requestContextSchema
        }
      });
      const resolved = await promptBlockStore.getByIdResolved(id, { status: "draft" });
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve created prompt block" });
      }
      const latestVersion = await promptBlockStore.getLatestVersion(id);
      const hasDraft = !!(latestVersion && (!resolved.activeVersionId || latestVersion.id !== resolved.activeVersionId));
      return { ...resolved, hasDraft };
    } 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,
    requestContextSchema
  }) => {
    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,
        requestContextSchema
      });
      const configFields = { name, description, content, rules, requestContextSchema };
      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" });
      }
      const latestVersion = await promptBlockStore.getLatestVersion(storedPromptBlockId);
      const hasDraft = !!(latestVersion && (!resolved.activeVersionId || latestVersion.id !== resolved.activeVersionId));
      return { ...resolved, hasDraft };
    } 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-2GOCJDE2.js.map
//# sourceMappingURL=chunk-2GOCJDE2.js.map