import { createClient, type Client as LibSQLClient } from "@libsql/client";

interface DatabaseConfig {
  url: string;
  authToken?: string;
  concurrentConnections?: number;
  connectTimeoutMs?: number;
}

export class DatabaseManager {
  private static instance: DatabaseManager;
  private client: LibSQLClient | null = null;
  private config: DatabaseConfig;

  private constructor(config: DatabaseConfig) {
    this.config = config;
  }

  static getInstance(config: DatabaseConfig): DatabaseManager {
    if (!DatabaseManager.instance) {
      DatabaseManager.instance = new DatabaseManager(config);
    }
    return DatabaseManager.instance;
  }

  initialize(): LibSQLClient {
    if (!this.client) {
      this.client = createClient({
        url: this.config.url,
        authToken: this.config.authToken,
      });
    }
    return this.client;
  }

  getClient(): LibSQLClient {
    if (!this.client) {
      return this.initialize();
    }
    return this.client;
  }

  async close(): Promise<void> {
    if (this.client) {
      await this.client.close();
      this.client = null;
    }
  }

  async execute(query: string, params?: unknown[]): Promise<void> {
    const client = this.getClient();
    await client.execute(query, params as any);
  }

  async query<T>(query: string, params?: unknown[]): Promise<T[]> {
    const client = this.getClient();
    const result = await client.execute(query, params as any);
    return result.rows as T[];
  }
}

export function createDatabaseManager(config: DatabaseConfig): DatabaseManager {
  return DatabaseManager.getInstance(config);
}
