'use strict';

var chunkTD4U2UEE_cjs = require('./chunk-TD4U2UEE.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-scorers.ts
var SCORER_SNAPSHOT_CONFIG_FIELDS = [
  "name",
  "description",
  "type",
  "model",
  "instructions",
  "scoreRange",
  "presetConfig",
  "defaultSampling"
];
var LIST_STORED_SCORERS_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/scorers",
  responseType: "json",
  queryParamSchema: chunkTD4U2UEE_cjs.listStoredScorersQuerySchema,
  responseSchema: chunkTD4U2UEE_cjs.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, requestContext }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scope = await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext);
      const result = await scorerStore.listResolved({
        page,
        perPage,
        orderBy,
        status,
        authorId,
        metadata: chunkDRDVJ35H_cjs.scopeStoredResourceMetadata(metadata, scope)
      });
      return result;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error listing stored scorer definitions");
    }
  }
});
var GET_STORED_SCORER_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "GET",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: chunkTD4U2UEE_cjs.storedScorerIdPathParams,
  queryParamSchema: chunkDIG2K5CV_cjs.statusQuerySchema,
  responseSchema: chunkTD4U2UEE_cjs.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, requestContext }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const scorer = await scorerStore.getByIdResolved(storedScorerId, { status });
      if (!scorer) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(scorer, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      return scorer;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error getting stored scorer definition");
    }
  }
});
var CREATE_STORED_SCORER_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "POST",
  path: "/stored/scorers",
  responseType: "json",
  bodySchema: chunkTD4U2UEE_cjs.createStoredScorerBodySchema,
  responseSchema: chunkTD4U2UEE_cjs.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,
    requestContext
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const id = providedId || chunkDRDVJ35H_cjs.toSlug(name);
      if (!id) {
        throw new chunk64ITUOXI_cjs.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 chunk64ITUOXI_cjs.HTTPException(409, { message: `Scorer definition with id ${id} already exists` });
      }
      await scorerStore.create({
        scorerDefinition: {
          id,
          authorId,
          metadata: chunkDRDVJ35H_cjs.scopeStoredResourceMetadata(metadata, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext)),
          name,
          description,
          type,
          model,
          instructions,
          scoreRange,
          presetConfig,
          defaultSampling
        }
      });
      const resolved = await scorerStore.getByIdResolved(id, { status: "draft" });
      if (!resolved) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve created scorer definition" });
      }
      return resolved;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error creating stored scorer definition");
    }
  }
});
var UPDATE_STORED_SCORER_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "PATCH",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: chunkTD4U2UEE_cjs.storedScorerIdPathParams,
  bodySchema: chunkTD4U2UEE_cjs.updateStoredScorerBodySchema,
  responseSchema: chunkTD4U2UEE_cjs.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,
    requestContext
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} 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 updatedScorer = await scorerStore.update({
        id: storedScorerId,
        authorId,
        ...scopedMetadata !== void 0 ? { metadata: scopedMetadata } : {},
        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 chunk2XZ2466F_cjs.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 chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to resolve updated scorer definition" });
      }
      return resolved;
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error updating stored scorer definition");
    }
  }
});
var DELETE_STORED_SCORER_ROUTE = chunkN54Q3AQR_cjs.createRoute({
  method: "DELETE",
  path: "/stored/scorers/:storedScorerId",
  responseType: "json",
  pathParamSchema: chunkTD4U2UEE_cjs.storedScorerIdPathParams,
  responseSchema: chunkTD4U2UEE_cjs.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, requestContext }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const scorerStore = await storage.getStore("scorerDefinitions");
      if (!scorerStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Scorer definitions storage domain is not available" });
      }
      const existing = await scorerStore.getById(storedScorerId);
      if (!existing) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Stored scorer definition with id ${storedScorerId} not found` });
      }
      chunkDRDVJ35H_cjs.assertStoredResourceScope(existing, await chunkDRDVJ35H_cjs.getStoredResourceScope(mastra, requestContext));
      await scorerStore.delete(storedScorerId);
      mastra.getEditor()?.scorer.clearCache(storedScorerId);
      return { success: true, message: `Scorer definition ${storedScorerId} deleted successfully` };
    } catch (error) {
      return chunkZ7LCIYK7_cjs.handleError(error, "Error deleting stored scorer definition");
    }
  }
});

exports.CREATE_STORED_SCORER_ROUTE = CREATE_STORED_SCORER_ROUTE;
exports.DELETE_STORED_SCORER_ROUTE = DELETE_STORED_SCORER_ROUTE;
exports.GET_STORED_SCORER_ROUTE = GET_STORED_SCORER_ROUTE;
exports.LIST_STORED_SCORERS_ROUTE = LIST_STORED_SCORERS_ROUTE;
exports.UPDATE_STORED_SCORER_ROUTE = UPDATE_STORED_SCORER_ROUTE;
//# sourceMappingURL=chunk-RDU2H7FF.cjs.map
//# sourceMappingURL=chunk-RDU2H7FF.cjs.map