import { VersionedStorageDomain, normalizePerPage, calculatePagination, FilesystemVersionedHelpers } from './chunk-RJLFW5PH.js';
import { deepEqual } from './chunk-6YQ4H5JS.js';

// src/storage/domains/scorer-definitions/base.ts
var ScorerDefinitionsStorage = class extends VersionedStorageDomain {
  listKey = "scorerDefinitions";
  versionMetadataFields = [
    "id",
    "scorerDefinitionId",
    "versionNumber",
    "changedFields",
    "changeMessage",
    "createdAt"
  ];
  constructor() {
    super({
      component: "STORAGE",
      name: "SCORER_DEFINITIONS"
    });
  }
};

// src/storage/domains/scorer-definitions/inmemory.ts
var InMemoryScorerDefinitionsStorage = class extends ScorerDefinitionsStorage {
  db;
  constructor({ db }) {
    super();
    this.db = db;
  }
  async dangerouslyClearAll() {
    this.db.scorerDefinitions.clear();
    this.db.scorerDefinitionVersions.clear();
  }
  // ==========================================================================
  // Scorer Definition CRUD Methods
  // ==========================================================================
  async getById(id) {
    const scorer = this.db.scorerDefinitions.get(id);
    return scorer ? this.deepCopyScorer(scorer) : null;
  }
  async create(input) {
    const { scorerDefinition } = input;
    if (this.db.scorerDefinitions.has(scorerDefinition.id)) {
      throw new Error(`Scorer definition with id ${scorerDefinition.id} already exists`);
    }
    const now = /* @__PURE__ */ new Date();
    const newScorer = {
      id: scorerDefinition.id,
      status: "draft",
      activeVersionId: void 0,
      authorId: scorerDefinition.authorId,
      metadata: scorerDefinition.metadata,
      createdAt: now,
      updatedAt: now
    };
    this.db.scorerDefinitions.set(scorerDefinition.id, newScorer);
    const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = scorerDefinition;
    const versionId = crypto.randomUUID();
    await this.createVersion({
      id: versionId,
      scorerDefinitionId: scorerDefinition.id,
      versionNumber: 1,
      ...snapshotConfig,
      changedFields: Object.keys(snapshotConfig),
      changeMessage: "Initial version"
    });
    return this.deepCopyScorer(newScorer);
  }
  async update(input) {
    const { id, ...updates } = input;
    const existingScorer = this.db.scorerDefinitions.get(id);
    if (!existingScorer) {
      throw new Error(`Scorer definition with id ${id} not found`);
    }
    const { authorId, activeVersionId, metadata, status } = updates;
    const updatedScorer = {
      ...existingScorer,
      ...authorId !== void 0 && { authorId },
      ...activeVersionId !== void 0 && { activeVersionId },
      ...status !== void 0 && { status },
      ...metadata !== void 0 && {
        metadata: { ...existingScorer.metadata, ...metadata }
      },
      updatedAt: /* @__PURE__ */ new Date()
    };
    this.db.scorerDefinitions.set(id, updatedScorer);
    return this.deepCopyScorer(updatedScorer);
  }
  async delete(id) {
    this.db.scorerDefinitions.delete(id);
    await this.deleteVersionsByParentId(id);
  }
  async list(args) {
    const { page = 0, perPage: perPageInput, orderBy, authorId, metadata, status } = args || {};
    const { field, direction } = this.parseOrderBy(orderBy);
    const perPage = normalizePerPage(perPageInput, 100);
    if (page < 0) {
      throw new Error("page must be >= 0");
    }
    const maxOffset = Number.MAX_SAFE_INTEGER / 2;
    if (page * perPage > maxOffset) {
      throw new Error("page value too large");
    }
    let scorers = Array.from(this.db.scorerDefinitions.values());
    if (status) {
      scorers = scorers.filter((scorer) => scorer.status === status);
    }
    if (authorId !== void 0) {
      scorers = scorers.filter((scorer) => scorer.authorId === authorId);
    }
    if (metadata && Object.keys(metadata).length > 0) {
      scorers = scorers.filter((scorer) => {
        if (!scorer.metadata) return false;
        return Object.entries(metadata).every(([key, value]) => deepEqual(scorer.metadata[key], value));
      });
    }
    const sortedScorers = this.sortScorers(scorers, field, direction);
    const clonedScorers = sortedScorers.map((scorer) => this.deepCopyScorer(scorer));
    const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
    return {
      scorerDefinitions: clonedScorers.slice(offset, offset + perPage),
      total: clonedScorers.length,
      page,
      perPage: perPageForResponse,
      hasMore: offset + perPage < clonedScorers.length
    };
  }
  // ==========================================================================
  // Scorer Definition Version Methods
  // ==========================================================================
  async createVersion(input) {
    if (this.db.scorerDefinitionVersions.has(input.id)) {
      throw new Error(`Version with id ${input.id} already exists`);
    }
    for (const version2 of this.db.scorerDefinitionVersions.values()) {
      if (version2.scorerDefinitionId === input.scorerDefinitionId && version2.versionNumber === input.versionNumber) {
        throw new Error(
          `Version number ${input.versionNumber} already exists for scorer definition ${input.scorerDefinitionId}`
        );
      }
    }
    const version = {
      ...input,
      createdAt: /* @__PURE__ */ new Date()
    };
    this.db.scorerDefinitionVersions.set(input.id, this.deepCopyVersion(version));
    return this.deepCopyVersion(version);
  }
  async getVersion(id) {
    const version = this.db.scorerDefinitionVersions.get(id);
    return version ? this.deepCopyVersion(version) : null;
  }
  async getVersionByNumber(scorerDefinitionId, versionNumber) {
    for (const version of this.db.scorerDefinitionVersions.values()) {
      if (version.scorerDefinitionId === scorerDefinitionId && version.versionNumber === versionNumber) {
        return this.deepCopyVersion(version);
      }
    }
    return null;
  }
  async getLatestVersion(scorerDefinitionId) {
    let latest = null;
    for (const version of this.db.scorerDefinitionVersions.values()) {
      if (version.scorerDefinitionId === scorerDefinitionId) {
        if (!latest || version.versionNumber > latest.versionNumber) {
          latest = version;
        }
      }
    }
    return latest ? this.deepCopyVersion(latest) : null;
  }
  async listVersions(input) {
    const { scorerDefinitionId, page = 0, perPage: perPageInput, orderBy } = input;
    const { field, direction } = this.parseVersionOrderBy(orderBy);
    const perPage = normalizePerPage(perPageInput, 20);
    if (page < 0) {
      throw new Error("page must be >= 0");
    }
    const maxOffset = Number.MAX_SAFE_INTEGER / 2;
    if (page * perPage > maxOffset) {
      throw new Error("page value too large");
    }
    let versions = Array.from(this.db.scorerDefinitionVersions.values()).filter(
      (v) => v.scorerDefinitionId === scorerDefinitionId
    );
    versions = this.sortVersions(versions, field, direction);
    const clonedVersions = versions.map((v) => this.deepCopyVersion(v));
    const total = clonedVersions.length;
    const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
    const paginatedVersions = clonedVersions.slice(offset, offset + perPage);
    return {
      versions: paginatedVersions,
      total,
      page,
      perPage: perPageForResponse,
      hasMore: offset + perPage < total
    };
  }
  async deleteVersion(id) {
    this.db.scorerDefinitionVersions.delete(id);
  }
  async deleteVersionsByParentId(entityId) {
    const idsToDelete = [];
    for (const [id, version] of this.db.scorerDefinitionVersions.entries()) {
      if (version.scorerDefinitionId === entityId) {
        idsToDelete.push(id);
      }
    }
    for (const id of idsToDelete) {
      this.db.scorerDefinitionVersions.delete(id);
    }
  }
  async countVersions(scorerDefinitionId) {
    let count = 0;
    for (const version of this.db.scorerDefinitionVersions.values()) {
      if (version.scorerDefinitionId === scorerDefinitionId) {
        count++;
      }
    }
    return count;
  }
  // ==========================================================================
  // Private Helper Methods
  // ==========================================================================
  deepCopyScorer(scorer) {
    return {
      ...scorer,
      metadata: scorer.metadata ? { ...scorer.metadata } : scorer.metadata
    };
  }
  deepCopyVersion(version) {
    return {
      ...version,
      model: version.model ? JSON.parse(JSON.stringify(version.model)) : version.model,
      scoreRange: version.scoreRange ? JSON.parse(JSON.stringify(version.scoreRange)) : version.scoreRange,
      presetConfig: version.presetConfig ? JSON.parse(JSON.stringify(version.presetConfig)) : version.presetConfig,
      defaultSampling: version.defaultSampling ? JSON.parse(JSON.stringify(version.defaultSampling)) : version.defaultSampling,
      changedFields: version.changedFields ? [...version.changedFields] : version.changedFields
    };
  }
  sortScorers(scorers, field, direction) {
    return scorers.sort((a, b) => {
      const aValue = a[field].getTime();
      const bValue = b[field].getTime();
      return direction === "ASC" ? aValue - bValue : bValue - aValue;
    });
  }
  sortVersions(versions, field, direction) {
    return versions.sort((a, b) => {
      let aVal;
      let bVal;
      if (field === "createdAt") {
        aVal = a.createdAt.getTime();
        bVal = b.createdAt.getTime();
      } else {
        aVal = a.versionNumber;
        bVal = b.versionNumber;
      }
      return direction === "ASC" ? aVal - bVal : bVal - aVal;
    });
  }
};

// src/storage/domains/scorer-definitions/filesystem.ts
var FilesystemScorerDefinitionsStorage = class extends ScorerDefinitionsStorage {
  helpers;
  constructor({ db }) {
    super();
    this.helpers = new FilesystemVersionedHelpers({
      db,
      entitiesFile: "scorer-definitions.json",
      parentIdField: "scorerDefinitionId",
      name: "FilesystemScorerDefinitionsStorage",
      versionMetadataFields: [
        "id",
        "scorerDefinitionId",
        "versionNumber",
        "changedFields",
        "changeMessage",
        "createdAt"
      ]
    });
  }
  async init() {
    await this.helpers.db.init();
  }
  async dangerouslyClearAll() {
    await this.helpers.dangerouslyClearAll();
  }
  async getById(id) {
    return this.helpers.getById(id);
  }
  async create(input) {
    const { scorerDefinition } = input;
    const now = /* @__PURE__ */ new Date();
    const entity = {
      id: scorerDefinition.id,
      status: "draft",
      activeVersionId: void 0,
      authorId: scorerDefinition.authorId,
      metadata: scorerDefinition.metadata,
      createdAt: now,
      updatedAt: now
    };
    await this.helpers.createEntity(scorerDefinition.id, entity);
    const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = scorerDefinition;
    const versionId = crypto.randomUUID();
    await this.createVersion({
      id: versionId,
      scorerDefinitionId: scorerDefinition.id,
      versionNumber: 1,
      ...snapshotConfig,
      changedFields: Object.keys(snapshotConfig),
      changeMessage: "Initial version"
    });
    return structuredClone(entity);
  }
  async update(input) {
    const { id, ...updates } = input;
    return this.helpers.updateEntity(id, updates);
  }
  async delete(id) {
    await this.helpers.deleteEntity(id);
  }
  async list(args) {
    const { page, perPage, orderBy, authorId, metadata, status } = args || {};
    const result = await this.helpers.listEntities({
      page,
      perPage,
      orderBy,
      listKey: "scorerDefinitions",
      filters: { authorId, metadata, status }
    });
    return result;
  }
  async createVersion(input) {
    return this.helpers.createVersion(input);
  }
  async getVersion(id) {
    return this.helpers.getVersion(id);
  }
  async getVersionByNumber(scorerDefinitionId, versionNumber) {
    return this.helpers.getVersionByNumber(scorerDefinitionId, versionNumber);
  }
  async getLatestVersion(scorerDefinitionId) {
    return this.helpers.getLatestVersion(scorerDefinitionId);
  }
  async listVersions(input) {
    const result = await this.helpers.listVersions(input, "scorerDefinitionId");
    return result;
  }
  async deleteVersion(id) {
    await this.helpers.deleteVersion(id);
  }
  async deleteVersionsByParentId(entityId) {
    await this.helpers.deleteVersionsByParentId(entityId);
  }
  async countVersions(scorerDefinitionId) {
    return this.helpers.countVersions(scorerDefinitionId);
  }
};

export { FilesystemScorerDefinitionsStorage, InMemoryScorerDefinitionsStorage, ScorerDefinitionsStorage };
//# sourceMappingURL=chunk-WJC36CEL.js.map
//# sourceMappingURL=chunk-WJC36CEL.js.map