import mysql from "mysql2/promise";

function databaseUrl() {
  if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
  const host = process.env.MYSQL_HOST ?? "127.0.0.1";
  const port = process.env.MYSQL_PORT ?? "3306";
  const user = encodeURIComponent(process.env.MYSQL_USER ?? "koc");
  const password = encodeURIComponent(process.env.MYSQL_PASSWORD ?? "");
  const database = process.env.MYSQL_DATABASE ?? "koc_loop";
  return `mysql://${user}:${password}@${host}:${port}/${database}`;
}
const connection = await mysql.createConnection({
  uri: databaseUrl(),
  charset: "utf8mb4",
  timezone: "Z",
});
try {
  const [rows] = await connection.query(
    "SELECT COUNT(*) AS table_count FROM information_schema.tables WHERE table_schema = DATABASE()",
  );
  console.info(`database ready, tables=${Number(rows[0]?.table_count ?? 0)}`);
} finally {
  await connection.end();
}
