import{eq as a,and as u,desc as c}from"drizzle-orm";import{VERSION_NOT_SPECIFIED as f}from"@redocly/theme/core/constants";import{entitiesTable as e}from"../../../../../providers/database/databases/sqlite-db/schemas/entities-table.js";import{compareVersionsDescending as m}from"../../../utils/version-compare.js";class p{db;constructor(t){this.db=t}async markAllVersionsAsNotDefault(t){await this.db.client.update(e).set({isDefaultVersion:!1}).where(u(a(e.key,t),a(e.isDefaultVersion,!0))).run()}async doesVersionExist(t,n){return await this.db.client.select().from(e).where(u(a(e.key,t),a(e.version,n))).get()!==void 0}async getOrderedVersionListForKey(t){return(await this.db.client.select({version:e.version,isDefaultVersion:e.isDefaultVersion,revision:e.revision,createdAt:e.createdAt}).from(e).where(u(a(e.key,t))).orderBy(c(e.createdAt)).all()).map(i=>({version:i.version,isDefaultVersion:!!i.isDefaultVersion,revision:i.revision,createdAt:new Date(i.createdAt)}))}getLatestVersion(t){const n=t.find(r=>r.isDefaultVersion);if(n)return n;const{versionedEntities:i,unversionedEntities:d}=t.reduce((r,s)=>(s.version!==null&&s.version!==f?r.versionedEntities.push(s):r.unversionedEntities.push(s),r),{versionedEntities:[],unversionedEntities:[]});if(i.length>0){i.sort((o,l)=>m(o.version,l.version));const r=i[0].version,s=i.filter(o=>o.version===r);return s.sort((o,l)=>l.createdAt.getTime()-o.createdAt.getTime()),s[0]}return d.length>0?(d.sort((r,s)=>s.createdAt.getTime()-r.createdAt.getTime()),d[0]):null}}export{p as VersionRepository};
