'use strict';

var chunkIABGFWY2_cjs = require('./chunk-IABGFWY2.cjs');
var chunk2XZ2466F_cjs = require('./chunk-2XZ2466F.cjs');
var chunkDIG2K5CV_cjs = require('./chunk-DIG2K5CV.cjs');
var chunkDRDVJ35H_cjs = require('./chunk-DRDVJ35H.cjs');
var chunkZ7LCIYK7_cjs = require('./chunk-Z7LCIYK7.cjs');
var chunkN54Q3AQR_cjs = require('./chunk-N54Q3AQR.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');

// 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 = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/prompt-blocks",
  responseType: "json",
  queryParamSchema: chunkIABGFWY2_cjs.listStoredPromptBlocksQuerySchema,
  responseSchema: chunkIABGFWY2_cjs.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, requestContext }) => {
    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 scope = await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext);
      const result = await promptBlockStore.listResolved({
        page,
        perPage,
        orderBy,
        status,
        authorId,
        metadata: chunkDRDVJ35H_cjs.scopeStoredResourceMetadata(metadata, scope)
      });
      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 chunkZ7LCIYK7_cjs.handleError(error, "Error listing stored prompt blocks");
    }
  }
});
var GET_STORED_PROMPT_BLOCK_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/prompt-blocks/:storedPromptBlockId",
  responseType: "json",
  pathParamSchema: chunkIABGFWY2_cjs.storedPromptBlockIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.statusQuerySchema,
  responseSchema: chunkIABGFWY2_cjs.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, requestContext }) => {
    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` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(promptBlock, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      const latestVersion = await promptBlockStore.getLatestVersion(storedPromptBlockId);
      return { ...promptBlock, hasDraft: computeHasDraft(latestVersion, promptBlock.activeVersionId) };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting stored prompt block");
    }
  }
});
var CREATE_STORED_PROMPT_BLOCK_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/stored/prompt-blocks",
  responseType: "json",
  bodySchema: chunkIABGFWY2_cjs.createStoredPromptBlockBodySchema,
  responseSchema: chunkIABGFWY2_cjs.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,
    requestContext
  }) => {
    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 || chunkDRDVJ35H_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: chunkDRDVJ35H_cjs.scopeStoredResourceMetadata(metadata, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext)),
          name,
          description,
          content,
          rules,
          requestContextSchema
        }
      });
      const resolved = await promptBlockStore.getByIdResolved(id, { status: "draft" });
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.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 chunkZ7LCIYK7_cjs.handleError(error, "Error creating stored prompt block");
    }
  }
});
var UPDATE_STORED_PROMPT_BLOCK_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "PATCH",
  path: "/stored/prompt-blocks/:storedPromptBlockId",
  responseType: "json",
  pathParamSchema: chunkIABGFWY2_cjs.storedPromptBlockIdPathParams,
  bodySchema: chunkIABGFWY2_cjs.updateStoredPromptBlockBodySchema,
  responseSchema: chunkIABGFWY2_cjs.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,
    requestContext
  }) => {
    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 scope = await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext);
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, scope);
      const scopedMetadata = metadata !== void 0 ? chunkDRDVJ35H_cjs.scopeStoredResourceMetadata({ ...existing.metadata ?? {}, ...metadata }, scope) : void 0;
      const updatedPromptBlock = await promptBlockStore.update({
        id: storedPromptBlockId,
        authorId,
        ...scopedMetadata !== void 0 ? { metadata: scopedMetadata } : {},
        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 chunk2XZ2466F_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" });
      }
      const latestVersion = await promptBlockStore.getLatestVersion(storedPromptBlockId);
      const hasDraft = !!(latestVersion && (!resolved.activeVersionId || latestVersion.id !== resolved.activeVersionId));
      return { ...resolved, hasDraft };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error updating stored prompt block");
    }
  }
});
var DELETE_STORED_PROMPT_BLOCK_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "DELETE",
  path: "/stored/prompt-blocks/:storedPromptBlockId",
  responseType: "json",
  pathParamSchema: chunkIABGFWY2_cjs.storedPromptBlockIdPathParams,
  responseSchema: chunkIABGFWY2_cjs.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, requestContext }) => {
    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` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      await promptBlockStore.delete(storedPromptBlockId);
      return {
        success: true,
        message: `Prompt block ${storedPromptBlockId} deleted successfully`
      };
    } catch (error) {
      return chunkZ7LCIYK7_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-UHKWQQBG.cjs.map
//# sourceMappingURL=chunk-UHKWQQBG.cjs.map