import { AiTenantModelAllowlist } from "../entities.js";
class AiTenantModelAllowlistRepository {
  constructor(em) {
    this.em = em;
  }
  async getForTenant(ctx) {
    if (!ctx?.tenantId) return null;
    const orgFilter = ctx.organizationId ?? null;
    const row = await this.em.findOne(AiTenantModelAllowlist, {
      tenantId: ctx.tenantId,
      organizationId: orgFilter,
      deletedAt: null
    });
    return row ?? null;
  }
  async getSnapshot(ctx) {
    const row = await this.getForTenant(ctx);
    if (!row) return null;
    return {
      allowedProviders: row.allowedProviders ?? null,
      allowedModelsByProvider: row.allowedModelsByProvider ?? {}
    };
  }
  async upsert(input, ctx) {
    if (!ctx?.tenantId) {
      throw new Error("AiTenantModelAllowlistRepository.upsert requires tenantId");
    }
    const orgFilter = ctx.organizationId ?? null;
    const providers = input.allowedProviders === void 0 ? null : input.allowedProviders;
    const models = input.allowedModelsByProvider ?? {};
    return this.em.transactional(async (tx) => {
      const existing = await tx.findOne(AiTenantModelAllowlist, {
        tenantId: ctx.tenantId,
        organizationId: orgFilter,
        deletedAt: null
      });
      if (existing) {
        existing.allowedProviders = providers;
        existing.allowedModelsByProvider = models;
        existing.updatedByUserId = ctx.userId ?? null;
        existing.updatedAt = /* @__PURE__ */ new Date();
        await tx.persist(existing).flush();
        return existing;
      }
      const row = tx.create(AiTenantModelAllowlist, {
        tenantId: ctx.tenantId,
        organizationId: orgFilter,
        allowedProviders: providers,
        allowedModelsByProvider: models,
        updatedByUserId: ctx.userId ?? null
      });
      await tx.persist(row).flush();
      return row;
    });
  }
  async clear(ctx) {
    if (!ctx?.tenantId) return false;
    const orgFilter = ctx.organizationId ?? null;
    return this.em.transactional(async (tx) => {
      const existing = await tx.findOne(AiTenantModelAllowlist, {
        tenantId: ctx.tenantId,
        organizationId: orgFilter,
        deletedAt: null
      });
      if (!existing) return false;
      existing.deletedAt = /* @__PURE__ */ new Date();
      await tx.persist(existing).flush();
      return true;
    });
  }
}
var AiTenantModelAllowlistRepository_default = AiTenantModelAllowlistRepository;
export {
  AiTenantModelAllowlistRepository,
  AiTenantModelAllowlistRepository_default as default
};
//# sourceMappingURL=AiTenantModelAllowlistRepository.js.map
