import{and as u,desc as v,eq as n,isNull as c,sql as d}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{compareVersions as h}from"../../../utils/version-compare.js";import{VersionRepository as m}from"./version-repository.js";import{buildSemanticVersionSortExpr as C}from"../utils/semantic-version-sort.js";import{normalizeRevisionFlags as y}from"../utils/normalize-revision-flags.js";class g{#i;#e;constructor(i){this.#e=i,this.#i=new m(i)}async getCurrentRevisionInfo({key:i,version:t,revision:r}){const o=await this.#t(i);if(!o)return{shouldSetNewCurrentRevision:!0,hasCurrentRevision:!1};if(t){const a=await this.#i.doesVersionExist(i,t),s=h(t,o.version)>0,l=o.version===f&&t!==f;if(!a&&(s||l))return{shouldSetNewCurrentRevision:!0,hasCurrentRevision:!0}}return t&&r&&t===o.version&&r>=o.revision?{shouldSetNewCurrentRevision:!0,hasCurrentRevision:!0}:{shouldSetNewCurrentRevision:!1,hasCurrentRevision:!0}}async markAllRevisionsAsNotCurrent(i){await this.#e.client.update(e).set({isCurrent:!1}).where(n(e.key,i)).run()}async ensureDefaultAndCurrentRevisionForKey(i){const t=await this.#i.getOrderedVersionListForKey(i),r=this.#i.getLatestVersion(t);r&&await this.#e.client.update(e).set({isDefaultVersion:!0,isCurrent:!0}).where(u(n(e.key,i),n(e.revision,r.revision),r.version?n(e.version,r.version):c(e.version))).run()}async shouldSkipRevisionCreation(i,t,r,o,a){if(o||a)return!1;const s=await this.#e.client.select({hash:e.hash,isDeleted:e.isDeleted}).from(e).where(u(n(e.key,i),t?n(e.version,t):c(e.version))).orderBy(v(e.revision)).limit(1).get();return!s||!!s.isDeleted?!1:s.hash===r}async#t(i){return await this.#e.client.select({version:e.version,revision:e.revision}).from(e).where(u(n(e.key,i),n(e.isCurrent,!0))).orderBy(v(e.revision)).limit(1).get()??null}async listEntityRevisions(i,t){const r=[n(e.key,i),n(e.isDeleted,!1),...t?[n(e.version,t)]:[]],a=(await this.#e.client.select({version:e.version,revision:e.revision,isCurrent:e.isCurrent,createdAt:e.createdAt,updatedAt:e.updatedAt,isDefaultVersion:e.isDefaultVersion}).from(e).where(u(...r)).orderBy(d`${C("version")} DESC`,d.raw("revision DESC")).all()).map(s=>({version:s.version,revision:s.revision??"",isCurrent:s.isCurrent!==null?s.isCurrent:!1,createdAt:s.createdAt,updatedAt:s.updatedAt,isDefaultVersion:s.isDefaultVersion!==null?s.isDefaultVersion:!1}));return y(a),a}}export{g as RevisionRepository};
