/**
 * MySQL connection + schema bootstrap
 * - Creates SCMS database if missing
 * - Creates tables if missing
 *
 * Uses mysql2/promise.
 */

const mysql = require('mysql2/promise');

const {
  DB_HOST,
  DB_USER,
  DB_PASSWORD,
  DB_NAME,
  DB_PORT
} = process.env;

const baseConfig = {
  host: DB_HOST || 'localhost',
  user: DB_USER || 'root',
  password: DB_PASSWORD || '',
  port: Number(DB_PORT || 3306)
};

/**
 * Creates a pooled connection to DB_NAME.
 */
async function createPool() {
  // 1) Ensure database exists
  const conn = await mysql.createConnection({ ...baseConfig });
  await conn.query(`CREATE DATABASE IF NOT EXISTS \`${DB_NAME || 'SCMS'}\``);
  await conn.end();

  // 2) Create pooled connection to the target database
  const pool = mysql.createPool({
    ...baseConfig,
    database: DB_NAME || 'SCMS',
    connectionLimit: 10,
    multipleStatements: true
  });

  // 3) Ensure schema exists
  await bootstrapSchema(pool);

  return pool;
}

/**
 * Bootsraps schema (tables + constraints).
 */
async function bootstrapSchema(pool) {
  const sql = `
    CREATE TABLE IF NOT EXISTS Supplier (
      supplierCode VARCHAR(50) PRIMARY KEY,
      supplierName VARCHAR(200) NOT NULL,
      telephone VARCHAR(50),
      address VARCHAR(255),
      email VARCHAR(200)
    );

    CREATE TABLE IF NOT EXISTS Shipment (
      shipmentNumber VARCHAR(50) PRIMARY KEY,
      shipmentDate DATE NOT NULL,
      shipmentStatus VARCHAR(50) NOT NULL,
      destination VARCHAR(200) NOT NULL,
      supplierCode VARCHAR(50) NOT NULL,
      CONSTRAINT fk_shipment_supplier
        FOREIGN KEY (supplierCode) REFERENCES Supplier(supplierCode)
        ON DELETE RESTRICT
        ON UPDATE CASCADE
    );

    CREATE TABLE IF NOT EXISTS Delivery (
      deliveryCode VARCHAR(50) PRIMARY KEY,
      deliveryDate DATE NOT NULL,
      quantityDelivered INT NOT NULL,
      deliveryStatus VARCHAR(50) NOT NULL,
      shipmentNumber VARCHAR(50) NOT NULL,
      CONSTRAINT fk_delivery_shipment
        FOREIGN KEY (shipmentNumber) REFERENCES Shipment(shipmentNumber)
        ON DELETE RESTRICT
        ON UPDATE CASCADE
    );

    CREATE TABLE IF NOT EXISTS User (
      id INT AUTO_INCREMENT PRIMARY KEY,
      username VARCHAR(100) UNIQUE NOT NULL,
      password VARCHAR(255) NOT NULL
    );
  `;

  await pool.query(sql);
}

let poolPromise;

function getPool() {
  if (!poolPromise) poolPromise = createPool();
  return poolPromise;
}

module.exports = { getPool };

