import { IDatabase, DatabaseConfig } from './types'
import { DrizzleDatabase } from './drizzle'

// Database factory - creates appropriate database instance based on config
export class DatabaseFactory {
  private static instance: IDatabase | null = null
  private static config: DatabaseConfig | null = null

  static async initialize(config: DatabaseConfig): Promise<IDatabase> {
    if (this.instance && this.config && this.isSameConfig(config)) {
      return this.instance
    }

    // Close existing connection if different config
    if (this.instance) {
      await this.instance.disconnect()
      this.instance = null
    }

    // Create new database instance based on type
    switch (config.type) {
      case 'sqlite':
        this.instance = new DrizzleDatabase(config)
        break

      case 'postgresql':
        // TODO: Implement PostgreSQLDatabase
        throw new Error('PostgreSQL implementation not yet available')

      case 'mysql':
        // TODO: Implement MySQLDatabase
        throw new Error('MySQL implementation not yet available')

      case 'mongodb':
        // TODO: Implement MongoDBDatabase
        throw new Error('MongoDB implementation not yet available')

      default:
        throw new Error(`Unsupported database type: ${config.type}`)
    }

    await this.instance.connect()
    this.config = config

    return this.instance
  }

  static getInstance(): IDatabase {
    if (!this.instance) {
      throw new Error('Database not initialized. Call initialize() first.')
    }
    return this.instance
  }

  static async disconnect(): Promise<void> {
    if (this.instance) {
      await this.instance.disconnect()
      this.instance = null
      this.config = null
    }
  }

  private static isSameConfig(config: DatabaseConfig): boolean {
    if (!this.config) return false

    return (
      this.config.type === config.type &&
      JSON.stringify(this.config.connection) === JSON.stringify(config.connection)
    )
  }
}

// Default configuration
export const defaultDatabaseConfig: DatabaseConfig = {
  type: 'sqlite',
  connection: {
    filename: './data/fitai.db'
  },
  options: {
    logging: process.env.NODE_ENV === 'development'
  }
}

// Convenience function to get database instance
export async function getDatabase(): Promise<IDatabase> {
  return await DatabaseFactory.initialize(defaultDatabaseConfig)
}