import 'server-only';
import mysql from 'mysql2/promise';
import { MYSQL } from './env';

/**
 * Baglanti havuzu. Next.js gelistirme modunda modul yeniden yuklendiginde
 * yeni havuz acilmasin diye global uzerinde saklanir.
 */
const globalForMysql = globalThis as unknown as { buelPool?: mysql.Pool };

export function pool(): mysql.Pool {
  if (!globalForMysql.buelPool) {
    globalForMysql.buelPool = mysql.createPool({
      host: MYSQL.host,
      port: MYSQL.port,
      user: MYSQL.user,
      password: MYSQL.password,
      database: MYSQL.database,
      waitForConnections: true,
      connectionLimit: Number(process.env.MYSQL_POOL_SIZE ?? 5),
      charset: 'utf8mb4_general_ci',
      timezone: 'Z',
      dateStrings: false,
      // Paylasimli hostinglerde bosta kalan baglantilar dusurulur.
      enableKeepAlive: true,
      keepAliveInitialDelay: 10_000,
    });
  }
  return globalForMysql.buelPool;
}

/** Sorgu parametrelerinde kullanilabilecek degerler. */
export type SqlParam = string | number | boolean | null | undefined | Date;

/** mysql2 undefined kabul etmez; tanimsiz degerleri NULL'a cevirir. */
function normalize(params: SqlParam[]) {
  return params.map((v) => (v === undefined ? null : v));
}

export async function query<T = Record<string, unknown>>(
  sql: string,
  params: SqlParam[] = []
): Promise<T[]> {
  const [rows] = await pool().execute(sql, normalize(params));
  return rows as T[];
}

export async function execute(sql: string, params: SqlParam[] = []): Promise<void> {
  await pool().execute(sql, normalize(params));
}
