import mysql from "mysql2/promise";
import { drizzle } from "drizzle-orm/mysql2";
import * as schema from "./schema";

const pool = mysql.createPool({
  host: process.env.DB_HOST || "localhost",
  port: Number(process.env.DB_PORT || 3306),
  user: process.env.DB_USER || "",
  password: process.env.DB_PASSWORD || "",
  database: process.env.DB_NAME || "",
  waitForConnections: true,
  connectionLimit: 10,
  charset: "utf8mb4",
});

export function getDb() {
  if (!process.env.DB_NAME || !process.env.DB_USER) {
    throw new Error("Konfigurasi MySQL belum lengkap. Isi DB_HOST, DB_PORT, DB_NAME, DB_USER, dan DB_PASSWORD pada Environment Variables cPanel.");
  }
  return drizzle(pool, { schema });
}
