'use strict';
import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';
import { like, sql } from 'drizzle-orm';
import _0x3881d1__default from 'fs';
import { isSQLiteSelection, isSelectQuery, hasConfig } from '../guards/db-type-guards.js';
import { createError } from '../../../fd-toolbox/errors/errors.js';
import { logInfo } from '../../../fd-toolbox/server/logging/logger.js';
import { runDrizzleMigration, runDrizzleGeneration } from '../utils/run-migration-command.js';
import { dbPragmas, dbErrorMessages, dbTransactions, getDrizzleDialectString, drizzleDialects } from '../constants/db-constants.js';
import { isTest } from '../../../fd-toolbox/lib/environments.js';
import { quoteSqlIdentifier, getSchemaTableNames } from '../utils/schema-table-names.js';

var __defProp=Object['defineProperty'],__name=(_0x4f843c,_0xa74fd3)=>__defProp(_0x4f843c,'name',{'value':_0xa74fd3,'configurable':!![]});class SqliteAdapter{static{__name(this,'SqliteAdapter');}#client;#db;#connectionString;#dbPath;#schema;constructor(_0x5bdb68){this.#connectionString=_0x5bdb68,_0x5bdb68&&(this.#dbPath=_0x5bdb68['replace']('file:',''));}['init'](_0x1e7307){this.#schema=_0x1e7307;if(this.#client&&!isTest())return;const {connectionString:_0x13ce42}=this.#ensureConnection();this.#client=createClient({'url':_0x13ce42}),this.#client['execute'](dbPragmas['enableForeignKeys']),this.#db=drizzle(this.#client,{'schema':_0x1e7307});}['getDb'](){if(!this.#db)throw createError(dbErrorMessages['dbNotInitialized']);return this.#db;}['getClient'](){if(!this.#client)throw createError(dbErrorMessages['dbClientNotInitialized']);return this.#client;}['createDynamicSelect'](_0x51135c,_0x365c67){const _0x4f09d9=this['getDb'](),_0x11127b=_0x365c67&&isSQLiteSelection(_0x365c67)?_0x4f09d9['select'](_0x365c67)['from'](_0x51135c)['$dynamic']():_0x4f09d9['select']()['from'](_0x51135c)['$dynamic']();if(!isSelectQuery(_0x11127b))throw createError(dbErrorMessages['drizzleUnexpectedObject']);return _0x11127b;}['getQueryConfig'](_0x47ed3c){if(hasConfig(_0x47ed3c))return _0x47ed3c['config'];throw createError(dbErrorMessages['invalidObject']);}async['beginUnsafeTransaction'](){await this['getClient']()['execute'](dbTransactions['beginTransaction']);}async['rollbackUnsafeTransaction'](){await this['getClient']()['execute'](dbTransactions['rollback']);}['getLikeExpression'](_0x2d66d7,_0x557d6b){return like(_0x2d66d7,_0x557d6b);}['getExtractDateExpression'](_0x25da2c){return sql`date(${_0x25da2c} / 1000, 'unixepoch')`;}['leftJoin'](_0x33482f,_0x3b9b33,_0x164c71){return _0x33482f['leftJoin'](_0x3b9b33,_0x164c71);}['innerJoin'](_0x5b4998,_0x48e78f,_0x206747){return _0x5b4998['innerJoin'](_0x48e78f,_0x206747);}['orderBy'](_0xb03520,..._0x73a85a){return _0xb03520['orderBy'](..._0x73a85a);}['groupBy'](_0x41d18f,..._0x6c60fd){return _0x41d18f['groupBy'](..._0x6c60fd);}['having'](_0x5817e9,_0x1d2f0a){return _0x5817e9['having'](_0x1d2f0a);}['limit'](_0x4ab4fd,_0x21005b){return _0x4ab4fd['limit'](_0x21005b);}['offset'](_0x8d4301,_0x5f1350){return _0x8d4301['offset'](_0x5f1350);}['where'](_0x448f61,_0x32a8cf){if(!_0x32a8cf)return _0x448f61;return _0x448f61['where'](_0x32a8cf);}['insert'](_0x432f0a){return this['getDb']()['insert'](_0x432f0a);}['update'](_0x2d46e2){return this['getDb']()['update'](_0x2d46e2);}['delete'](_0x348af1){return this['getDb']()['delete'](_0x348af1);}async['createDatabaseIfNotExists'](){return this.#ensureConnection(),Promise['resolve']();}async['dropDatabase'](){const {dbPath:_0x10b2de}=this.#ensureConnection();if(_0x3881d1__default['existsSync'](_0x10b2de))try{this.#client&&(this.#client['close'](),this.#client=void(-0x211e+0x7b1+0x196d),this.#db=void(0xbff*0x2+-0x142b*0x1+-0x59*0xb)),await _0x3881d1__default['promises']['unlink'](_0x10b2de),_0x3881d1__default['existsSync'](_0x10b2de+'-wal')&&await _0x3881d1__default['promises']['unlink'](_0x10b2de+'-wal'),_0x3881d1__default['existsSync'](_0x10b2de+'-shm')&&await _0x3881d1__default['promises']['unlink'](_0x10b2de+'-shm'),logInfo('Database\x20'+_0x10b2de+'\x20successfully\x20deleted');}catch(_0x352e76){throw createError('Error\x20deleting\x20SQLite\x20database\x20file:\x20'+_0x10b2de,_0x352e76);}else logInfo('Database\x20'+_0x10b2de+'\x20not\x20found');}async['emptyAllTables'](){const _0x35c0eb=this['getClient'](),_0x1e7df2=this.#getSchemaTableNames();if(_0x1e7df2['length']===-0x11*-0x21d+-0x431+0xa94*-0x3)return;await _0x35c0eb['execute'](dbPragmas['disableForeignKeys']),await _0x35c0eb['execute'](dbTransactions['beginTransaction']);try{for(const _0x1ca9be of _0x1e7df2){await _0x35c0eb['execute']('DELETE\x20FROM\x20'+quoteSqlIdentifier(_0x1ca9be));}if(await this.#hasSqliteSequenceTable()){const _0x39f6e1=_0x1e7df2['map'](_0x39a319=>'\x27'+_0x39a319['replaceAll']('\x27','\x27\x27')+'\x27')['join'](',\x20');await _0x35c0eb['execute']('DELETE\x20FROM\x20sqlite_sequence\x20WHERE\x20name\x20IN\x20('+_0x39f6e1+')');}await _0x35c0eb['execute']('COMMIT');}catch(_0x2e75f1){await _0x35c0eb['execute'](dbTransactions['rollback']);throw _0x2e75f1;}finally{await _0x35c0eb['execute'](dbPragmas['enableForeignKeys']);}}async['runMigrations'](){const {connectionString:_0x4ced1b}=this.#ensureConnection();await runDrizzleMigration({'dialect':getDrizzleDialectString(drizzleDialects['sqlite']),'dbUrl':_0x4ced1b});}async['generateMigrations'](_0x192df9){this.#ensureConnection(),await runDrizzleGeneration(_0x192df9);}async #hasSqliteSequenceTable(){const _0x5b4a36=await this['getClient']()['execute']('SELECT\x20name\x20FROM\x20sqlite_master\x20WHERE\x20type\x20=\x20\x27table\x27\x20AND\x20name\x20=\x20\x27sqlite_sequence\x27');return _0x5b4a36['rows']['length']>0x10b6*-0x1+-0x1*0x1e3d+-0x2c3*-0x11;}#getSchemaTableNames(){if(!this.#schema)throw createError(dbErrorMessages['dbNotInitialized']);return getSchemaTableNames(this.#schema);}#ensureConnection(){if(!this.#connectionString||!this.#dbPath)throw createError(dbErrorMessages['dbConnectionStringNotProvided']);return {'connectionString':this.#connectionString,'dbPath':this.#dbPath};}}

export { SqliteAdapter };
