import{ulid as l}from"ulid";import{logger as s}from"../../../tools/notifiers/logger.js";import{BaseService as h}from"../../../providers/database/base-service.js";import{InstanceCacheResolver as y}from"../../../providers/database/instance-cache-resolver.js";import{shaHex as m}from"../../../utils/crypto/sha-hex.js";import{slug as v}from"../../../../utils/slugger.js";import{withTimestamp as f}from"../../../utils/time/with-timestamp.js";import{ScorecardsConfigRepository as g}from"./repositories/scorecards-config-repository.js";class c extends h{static#e=new y(async e=>new c(await g.create(e),e));constructor(e,r){super(r,{repository:e,createRepository:g.create})}static async getInstance(e){return c.#e.get(e)}async syncConfig(e,r){const n=new Set;(!Array.isArray(e)||e.length===0)&&s.verbose("No scorecard configs to sync"),s.verbose(`Starting scorecard config sync for ${e.length} config(s)`);for(const t of e)try{const i=t.key;if(!/^[a-z0-9-]+$/i.test(i)){s.error(`Skipping invalid scorecard config item: key "${i}" does not match kebab-case format (letters, numbers, and dashes only)`,{scorecard:t});continue}n.add(i);const o=this.#i(t),a=await this.runRead(d=>d.findActiveConfigByKey(i));if(a){if(a.configHash===o){s.verbose(`Config "${i}" unchanged, skipping update`);continue}s.verbose(`Updating config "${i}"`),await this.#r(a.id,t,o)}else s.verbose(`Inserting new config "${i}"`),await this.#t(i,t,o);r&&await r(i)}catch(i){s.error("Error processing scorecard config item:",{error:i.message??i,scorecard:t})}await this.#s(n),s.verbose("Sync scorecard configuration: success")}#i(e){const r=JSON.stringify({entities:e.entities,levels:e.levels});return m(r)}async#t(e,r,n){await this.runWrite(t=>t.insertConfig(f({id:`sc_${l()}`,key:e,slug:v(e),name:r.name,description:r.description??null,entitiesFilter:JSON.stringify(r.entities),levels:JSON.stringify(r.levels),configHash:n,archivedAt:null})))}async#r(e,r,n){const t=f({entitiesFilter:JSON.stringify(r.entities),levels:JSON.stringify(r.levels),configHash:n,archivedAt:null},{fields:["updatedAt"]});await this.runWrite(i=>i.updateConfigById(e,t))}async#s(e){const r=await this.runRead(t=>t.findAllActiveConfigs()),n=new Date().toISOString();for(const t of r)if(!e.has(t.key)){s.verbose(`Archiving removed config "${t.key}"`);try{await this.runWrite(i=>i.archiveConfigById(t.id,n))}catch(i){s.error(`Error archiving config item "${t.key}":`,i.message??i)}}}}export{c as ScorecardsConfigService};
