import mysql from "mysql2/promise";
import dotenv from "dotenv";

dotenv.config();

// Force the environment and database name to be the test DB
process.env.NODE_ENV = "test";
// Keep test DB name in sync with what the npm test script sets via DB_NAME env var.
// The npm test script sets DB_NAME=airpero_sass_test (one 's'), so we read from env.
process.env.DB_NAME = process.env.DB_NAME || "airpero_sass_test";

const TEST_DB_NAME = process.env.DB_NAME;

const dbConfig = {
  host: process.env.DB_HOST || "127.0.0.1",
  // IMPORTANT: Read DB_PORT from env — your MySQL runs on 3307, not the default 3306
  port: parseInt(process.env.DB_PORT || "3306", 10),
  user: process.env.DB_USER || process.env.DB_USERNAME || "root",
  password: process.env.DB_PASSWORD || "",
};

export async function setupTestDb() {
  let connection;
  try {
    // 1. Connect to MySQL without specifying a database
    connection = await mysql.createConnection(dbConfig);

    // 2. Create the test database if it does not exist
    await connection.query(`CREATE DATABASE IF NOT EXISTS \`${TEST_DB_NAME}\`;`);
    console.log(`📡 Database '${TEST_DB_NAME}' verified or created.`);
  } catch (error) {
    console.error("❌ Failed to verify/create test database:", error.message);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
    }
  }

  try {
    // Dynamically import db to ensure process.env.DB_NAME override is applied first
    const { default: db } = await import("../../src/models/index.js");

    await db.sequelize.authenticate();
    await db.sequelize.sync({ force: true });
    console.log("✅ Test database synchronized and schemas recreated.");

    // Seed initial Settings
    await db.Setting.bulkCreate([
      { key: "deposit_fee_percent", value: "0.5" },
      { key: "deposit_fee_cap", value: "100" },
      { key: "payout_fee_flat", value: "20" },
    ]);
    
    // Seed initial ServicePricing (the new fee system)
    await db.ServicePricing.bulkCreate([
      { serviceName: "wallet_deposit", currency: "NGN", customerPercentage: 0.005, customerMaxCap: 100 },
      { serviceName: "payout", currency: "NGN", customerFixedFee: 20 }
    ]);
    console.log("✅ Test database settings seeded.");

  } catch (error) {
    console.error("❌ Error setting up test database schemas:", error.message);
    throw error;
  }
}

export async function cleanUpTestDb() {
  try {
    const { default: db } = await import("../../src/models/index.js");
    await db.sequelize.close();
    console.log("✅ Sequelize connection closed successfully.");
  } catch (error) {
    console.error("❌ Error closing Sequelize database connection:", error.message);
  }
}
