import { listStoredScorersResponseSchema, listStoredScorersQuerySchema, getStoredScorerResponseSchema, storedScorerIdPathParams, createStoredScorerResponseSchema, createStoredScorerBodySchema, updateStoredScorerResponseSchema, updateStoredScorerBodySchema, deleteStoredScorerResponseSchema } from './chunk-BTRFBBRF.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-scorers.ts
var SCORER_SNAPSHOT_CONFIG_FIELDS = [
  "name",
  "description",
  "type",
  "model",
  "instructions",
  "scoreRange",
  "presetConfig",
  "defaultSampling"
];
var LIST_STORED_SCORERS_ROUTE = createRoute({
  method: "GET",
  path: "/stored/scorers",
  responseType: "json",
  queryParamSchema: listStoredScorersQuerySchema,
  responseSchema: listStoredScorersResponseSchema,
  summary: "List stored scorer definitions",
  description: "Returns a paginated list of all scorer definitions stored in the database",
  tags: ["Stored Scorers"],
  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 scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const result = await scorerStore.listResolved({
        page,
        perPage,
        orderBy,
        status,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return handleError(error, "Error listing stored scorer definitions");
    }
  }
});
var GET_STORED_SCORER_ROUTE = createRoute({
  method: "GET",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: storedScorerIdPathParams,
  queryParamSchema: statusQuerySchema,
  responseSchema: getStoredScorerResponseSchema,
  summary: "Get stored scorer definition by ID",
  description: "Returns a specific scorer definition 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 Scorers"],
  requiresAuth: true,
  handler: async ({ mastra, storedScorerId, status }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getByIdResolved(storedScorerId, { status });
      if (!scorer) {
        throw new HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      return scorer;
    } catch (error) {
      return handleError(error, "Error getting stored scorer definition");
    }
  }
});
var CREATE_STORED_SCORER_ROUTE = createRoute({
  method: "POST",
  path: "/stored/scorers",
  responseType: "json",
  bodySchema: createStoredScorerBodySchema,
  responseSchema: createStoredScorerResponseSchema,
  summary: "Create stored scorer definition",
  description: "Creates a new scorer definition in storage with the provided configuration",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({
    mastra,
    id: providedId,
    authorId,
    metadata,
    name,
    description,
    type,
    model,
    instructions,
    scoreRange,
    presetConfig,
    defaultSampling
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const id = providedId || toSlug(name);
      if (!id) {
        throw new HTTPException(400, {
          message: "Could not derive scorer definition ID from name. Please provide an explicit id."
        });
      }
      const existing = await scorerStore.getById(id);
      if (existing) {
        throw new HTTPException(409, { message: `Scorer definition with id ${id} already exists` });
      }
      await scorerStore.create({
        scorerDefinition: {
          id,
          authorId,
          metadata,
          name,
          description,
          type,
          model,
          instructions,
          scoreRange,
          presetConfig,
          defaultSampling
        }
      });
      const resolved = await scorerStore.getByIdResolved(id, { status: "draft" });
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve created scorer definition" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error creating stored scorer definition");
    }
  }
});
var UPDATE_STORED_SCORER_ROUTE = createRoute({
  method: "PATCH",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: storedScorerIdPathParams,
  bodySchema: updateStoredScorerBodySchema,
  responseSchema: updateStoredScorerResponseSchema,
  summary: "Update stored scorer definition",
  description: "Updates an existing scorer definition in storage with the provided fields",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({
    mastra,
    storedScorerId,
    // Metadata-level fields
    authorId,
    metadata,
    // Config fields (snapshot-level)
    name,
    description,
    type,
    model,
    instructions,
    scoreRange,
    presetConfig,
    defaultSampling
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      const updatedScorer = await scorerStore.update({
        id: storedScorerId,
        authorId,
        metadata,
        name,
        description,
        type,
        model,
        instructions,
        scoreRange,
        presetConfig,
        defaultSampling
      });
      const configFields = {
        name,
        description,
        type,
        model,
        instructions,
        scoreRange,
        presetConfig,
        defaultSampling
      };
      const providedConfigFields = Object.fromEntries(Object.entries(configFields).filter(([_, v]) => v !== void 0));
      await handleAutoVersioning(
        scorerStore,
        storedScorerId,
        "scorerDefinitionId",
        SCORER_SNAPSHOT_CONFIG_FIELDS,
        existing,
        updatedScorer,
        providedConfigFields
      );
      const editor = mastra.getEditor();
      if (editor) {
        editor.scorer.clearCache(storedScorerId);
      }
      const resolved = await scorerStore.getByIdResolved(storedScorerId, { status: "draft" });
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve updated scorer definition" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error updating stored scorer definition");
    }
  }
});
var DELETE_STORED_SCORER_ROUTE = createRoute({
  method: "DELETE",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: storedScorerIdPathParams,
  responseSchema: deleteStoredScorerResponseSchema,
  summary: "Delete stored scorer definition",
  description: "Deletes a scorer definition from storage by its unique identifier",
  tags: ["Stored Scorers"],
  requiresAuth: true,
  handler: async ({ mastra, storedScorerId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      await scorerStore.delete(storedScorerId);
      mastra.getEditor()?.scorer.clearCache(storedScorerId);
      return { success: true, message: `Scorer definition ${storedScorerId} deleted successfully` };
    } catch (error) {
      return handleError(error, "Error deleting stored scorer definition");
    }
  }
});

export { CREATE_STORED_SCORER_ROUTE, DELETE_STORED_SCORER_ROUTE, GET_STORED_SCORER_ROUTE, LIST_STORED_SCORERS_ROUTE, UPDATE_STORED_SCORER_ROUTE };
//# sourceMappingURL=chunk-JK3GI25F.js.map
//# sourceMappingURL=chunk-JK3GI25F.js.map