/**
 * Database connection and configuration for Turso/LibSQL
 */
import { createClient } from '@libsql/client';
export class DatabaseConnection {
    client = null;
    config;
    constructor(config) {
        this.config = config;
    }
    /**
     * Initialize the database connection
     */
    async connect() {
        if (this.client) {
            return; // Already connected
        }
        try {
            this.client = createClient({
                url: this.config.url,
                authToken: this.config.authToken,
                syncUrl: this.config.syncUrl,
            });
            // Test the connection
            await this.client.execute('SELECT 1');
            console.error('Database connected successfully');
        }
        catch (error) {
            console.error('Failed to connect to database:', error);
            throw new Error(`Database connection failed: ${error}`);
        }
    }
    /**
     * Get the database client
     */
    getClient() {
        if (!this.client) {
            throw new Error('Database not connected. Call connect() first.');
        }
        return this.client;
    }
    /**
     * Close the database connection
     */
    async disconnect() {
        if (this.client) {
            this.client.close();
            this.client = null;
            console.error('Database disconnected');
        }
    }
    /**
     * Execute a query with parameters
     */
    async execute(sql, params) {
        const client = this.getClient();
        try {
            const result = await client.execute({
                sql,
                args: params || [],
            });
            return result;
        }
        catch (error) {
            console.error('Database query error:', error);
            throw error;
        }
    }
    /**
     * Execute multiple queries in a transaction
     */
    async transaction(queries) {
        const client = this.getClient();
        try {
            const results = await client.batch(queries.map(query => ({
                sql: query.sql,
                args: query.params || [],
            })));
            return results;
        }
        catch (error) {
            console.error('Database transaction error:', error);
            throw error;
        }
    }
    /**
     * Check if the database is connected
     */
    isConnected() {
        return this.client !== null;
    }
    /**
     * Sync the database (for embedded replicas)
     */
    async sync() {
        if (this.client && 'sync' in this.client) {
            try {
                await this.client.sync();
                console.error('Database synced successfully');
            }
            catch (error) {
                console.error('Database sync error:', error);
                throw error;
            }
        }
    }
}
// Singleton instance
let dbInstance = null;
/**
 * Get or create the database connection instance
 */
export function getDatabase(config) {
    if (!dbInstance && config) {
        dbInstance = new DatabaseConnection(config);
    }
    if (!dbInstance) {
        throw new Error('Database not initialized. Provide config on first call.');
    }
    return dbInstance;
}
/**
 * Initialize database from environment variables
 */
export function initDatabaseFromEnv() {
    const config = {
        url: process.env.TURSO_URL || process.env.DATABASE_URL || '',
        authToken: process.env.TURSO_AUTH_TOKEN || process.env.DATABASE_AUTH_TOKEN || '',
        syncUrl: process.env.TURSO_SYNC_URL,
    };
    if (!config.url) {
        throw new Error('Database configuration missing. Set TURSO_URL environment variable.');
    }
    // For local file databases, auth token is not required
    if (!config.url.startsWith('file:') && !config.authToken) {
        throw new Error('Database auth token missing. Set TURSO_AUTH_TOKEN environment variable for remote databases.');
    }
    return getDatabase(config);
}
//# sourceMappingURL=connection.js.map