import { drizzle } from "drizzle-orm/mysql2";
import type { MySql2Database } from "drizzle-orm/mysql2";
import mysql from "mysql2/promise";
import { env } from "./env.js";

let pool: mysql.Pool | null = null;

export function getDb(): MySql2Database {
  if (!pool) {
    pool = mysql.createPool({
      uri: env.DATABASE_URL,
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0,
    });
  }
  return drizzle(pool);
}

/**
 * 全局 db 实例（模块装配时初始化，供 OutboxModule 等需要 db 引用的模块使用）。
 * 在 AppModule.onModuleInit 中通过 ensureDbInitialized() 确保已创建。
 */
let dbInstance: MySql2Database | null = null;

export function getDbInstance(): MySql2Database {
  if (!dbInstance) {
    dbInstance = getDb();
  }
  return dbInstance;
}

export async function closeDb(): Promise<void> {
  if (pool) {
    await pool.end();
    pool = null;
    dbInstance = null;
  }
}
