import {
  findOneWithDecryption,
  findWithDecryption
} from "@open-mercato/shared/lib/encryption/find";
import { AiAgentPromptOverride } from "../entities.js";
class AiAgentPromptOverrideRepository {
  constructor(em) {
    this.em = em;
  }
  async getLatest(agentId, ctx) {
    if (!agentId || !ctx?.tenantId) return null;
    const row = await findOneWithDecryption(
      this.em,
      AiAgentPromptOverride,
      {
        tenantId: ctx.tenantId,
        organizationId: ctx.organizationId ?? null,
        agentId
      },
      { orderBy: { version: "desc" } },
      { tenantId: ctx.tenantId ?? null, organizationId: ctx.organizationId ?? null }
    );
    return row ?? null;
  }
  async listVersions(agentId, ctx, limit = 10) {
    if (!agentId || !ctx?.tenantId) return [];
    const capped = Math.max(1, Math.min(Math.floor(limit), 100));
    const rows = await findWithDecryption(
      this.em,
      AiAgentPromptOverride,
      {
        tenantId: ctx.tenantId,
        organizationId: ctx.organizationId ?? null,
        agentId
      },
      {
        orderBy: { version: "desc" },
        limit: capped
      },
      { tenantId: ctx.tenantId ?? null, organizationId: ctx.organizationId ?? null }
    );
    return rows;
  }
  async save(input, ctx) {
    if (!ctx?.tenantId) {
      throw new Error("AiAgentPromptOverrideRepository.save requires tenantId");
    }
    if (!input?.agentId) {
      throw new Error("AiAgentPromptOverrideRepository.save requires agentId");
    }
    const sanitizedSections = sanitizeSections(input.sections);
    return this.em.transactional(async (tx) => {
      const latest = await findOneWithDecryption(
        tx,
        AiAgentPromptOverride,
        {
          tenantId: ctx.tenantId,
          organizationId: ctx.organizationId ?? null,
          agentId: input.agentId
        },
        { orderBy: { version: "desc" } },
        { tenantId: ctx.tenantId ?? null, organizationId: ctx.organizationId ?? null }
      );
      const nextVersion = (latest?.version ?? 0) + 1;
      const row = tx.create(AiAgentPromptOverride, {
        tenantId: ctx.tenantId,
        organizationId: ctx.organizationId ?? null,
        agentId: input.agentId,
        version: nextVersion,
        sections: sanitizedSections,
        notes: input.notes ?? null,
        createdByUserId: ctx.userId ?? null
      });
      await tx.persist(row).flush();
      return row;
    });
  }
}
function sanitizeSections(sections) {
  if (!sections || typeof sections !== "object") return {};
  const out = {};
  for (const [key, value] of Object.entries(sections)) {
    if (typeof value !== "string") continue;
    const trimmed = value.trim();
    if (!trimmed) continue;
    out[key] = value;
  }
  return out;
}
var AiAgentPromptOverrideRepository_default = AiAgentPromptOverrideRepository;
export {
  AiAgentPromptOverrideRepository,
  AiAgentPromptOverrideRepository_default as default
};
//# sourceMappingURL=AiAgentPromptOverrideRepository.js.map
