import { describe, it, expect } from "vitest";
import mysql from "mysql2/promise";

const shouldRun = process.env.RUN_DB_TESTS === "true";
const maybeDescribe = shouldRun ? describe : describe.skip;

const readEnv = (key: string): string => {
  const value = process.env[key];
  if (!value) {
    throw new Error(`Missing env var: ${key}`);
  }
  return value;
};

maybeDescribe("db smoke", () => {
  it("connecte et exécute SELECT 1 (lecture seule)", async () => {
    const host = readEnv("DB_HOST");
    const port = Number(process.env.DB_PORT ?? "3306");
    const user = readEnv("DB_USER");
    const database = readEnv("DB_NAME");
    const password = readEnv("DB_PASSWORD");

    const pool = mysql.createPool({
      host,
      port,
      user,
      password,
      database,
      connectionLimit: 1,
    });

    const [rows] = await pool.query("SELECT 1 as ok");
    await pool.end();

    const rowArray = Array.isArray(rows) ? rows : [];
    const first = rowArray[0] as { ok?: number } | undefined;
    expect(first?.ok ?? 0).toBe(1);
  });
});
