"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.db = void 0;
const libsql_1 = require("drizzle-orm/libsql");
const migrator_1 = require("drizzle-orm/libsql/migrator");
const client_1 = require("@libsql/client");
const paths_1 = require("./paths");
const schema = __importStar(require("./schema"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/**
 * Database class that handles initialization and provides access to the database
 */
class DatabaseClient {
    client = null;
    _drizzle = null;
    /**
     * Initialize the database connection
     */
    async init() {
        if (this.client) {
            return;
        }
        try {
            const dbPath = (0, paths_1.getDatabasePath)();
            console.log(`Initializing database at: ${dbPath}`);
            // Create database directory if it doesn't exist
            const dbDir = path_1.default.dirname(dbPath);
            if (!fs_1.default.existsSync(dbDir)) {
                fs_1.default.mkdirSync(dbDir, { recursive: true });
            }
            // Use file protocol for local libsql database
            this.client = (0, client_1.createClient)({
                url: `file:${dbPath}`,
            });
            // Create Drizzle instance
            this._drizzle = (0, libsql_1.drizzle)(this.client, { schema });
            // Check if migrations have already been applied
            const migrationsPath = path_1.default.resolve(__dirname, 'migrations');
            console.log('Migrations path:', migrationsPath);
            try {
                // Check if __drizzle_migrations table exists and has entries
                const existingMigrations = await this.client.execute('SELECT COUNT(*) as count FROM __drizzle_migrations');
                const migrationCount = existingMigrations.rows[0]?.count;
                if (migrationCount > 0) {
                    console.log(`Database already has ${migrationCount} migrations applied, skipping migration`);
                }
                else {
                    console.log('No migrations found, applying migrations...');
                    await (0, migrator_1.migrate)(this._drizzle, {
                        migrationsFolder: migrationsPath,
                    });
                    console.log('Database migrations applied successfully');
                }
            }
            catch (error) {
                // If __drizzle_migrations table doesn't exist, apply migrations
                console.log('Migrations table not found, applying migrations...');
                await (0, migrator_1.migrate)(this._drizzle, {
                    migrationsFolder: migrationsPath,
                });
                console.log('Database migrations applied successfully');
            }
            // Enable foreign keys
            await this.client.execute('PRAGMA foreign_keys = ON;');
            console.log('Database initialized successfully');
        }
        catch (error) {
            console.error('Failed to initialize database:', error);
            throw error;
        }
    }
    /**
     * Get the Drizzle ORM instance
     */
    get drizzle() {
        if (!this._drizzle) {
            throw new Error('Database not initialized. Call init() first.');
        }
        return this._drizzle;
    }
    /**
     * Initialize the database and return the drizzle instance
     * This is useful for ensuring the database is initialized before using it
     */
    async getDrizzle() {
        if (!this._drizzle) {
            await this.init();
        }
        return this._drizzle;
    }
    /**
     * Get the underlying libsql client
     */
    getClient() {
        if (!this.client) {
            throw new Error('Database not initialized. Call init() first.');
        }
        return this.client;
    }
    /**
     * Close the database connection
     */
    async close() {
        if (this.client) {
            // No specific close method needed for libsql client
            this.client = null;
            this._drizzle = null;
            console.log('Database connection closed');
        }
    }
}
// Create a singleton instance
exports.db = new DatabaseClient();
//# sourceMappingURL=db.js.map