import sqlite3 from 'node-sqlite3-wasm';
import path from 'path';
import { app } from 'electron';
import { initializeSchema, runMigrations } from './schema.js';

// Type alias for compatibility
export type Database = sqlite3.Database;

/**
 * DatabaseService - Manages SQLite database connection ONLY
 * No business logic, no CRUD operations
 * Just connection management and encryption key storage
 */
export class DatabaseService {
    private db: Database | null = null;
    private userEncryptionKey: string | null = null;
    private userId: string | null = null;

    constructor() {}

    /**
     * Initialize the database for a specific user
     * @param userId - User ID for encryption key
     * @param encryptionKey - User's encryption key (generated at first login)
     */
    initialize(userId: string, encryptionKey: string): void {
        if (this.db) {
            this.close();
        }
        
        const userDataPath:string = app.getPath('userData');
        const dbPath:string = path.join(userDataPath, `eritors-local.db`);

        this.db = new sqlite3.Database(dbPath);
        this.userEncryptionKey = encryptionKey;
        this.userId = userId;
        
        initializeSchema(this.db);
        
        runMigrations(this.db);
    }

    /**
     * Close the database connection
     */
    close(): void {
        if (this.db) {
            this.db.close();
            this.db = null;
            this.userEncryptionKey = null;
            this.userId = null;
        }
    }

    /**
     * Check if database is initialized
     */
    isInitialized(): boolean {
        return this.db !== null && this.userEncryptionKey !== null;
    }

    /**
     * Get database connection
     * Use this in repositories and model classes
     */
    getDb(): Database | null {
        return this.db;
    }

    /**
     * Get user encryption key
     */
    getEncryptionKey(): string | null {
        return this.userEncryptionKey;
    }

    /**
     * Get current user ID
     */
    getUserId(): string | null {
        return this.userId;
    }
}

// Singleton instance
let dbServiceInstance: DatabaseService | null = null;

export function getDatabaseService(): DatabaseService {
    if (!dbServiceInstance) {
        dbServiceInstance = new DatabaseService();
    }
    return dbServiceInstance;
}
