import mysql from 'mysql2/promise';

let pool: mysql.Pool | null = null;

export function getDb() {
  if (!pool) {
    pool = mysql.createPool({
      host: process.env.db_ip || '127.0.0.1',
      port: Number(process.env.db_port || 3306),
      user: process.env.db_username || 'recipe',
      password: process.env.db_password || 'pass',
      database: process.env.db_name || 'recipe_db',
      connectionLimit: 10,
      charset: 'utf8mb4',
    });
  }
  return pool;
}

export async function ensureSchema() {
  const db = getDb();
  await db.execute(`
    CREATE TABLE IF NOT EXISTS recipes (
      id BIGINT AUTO_INCREMENT PRIMARY KEY,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      source_url VARCHAR(1024) NOT NULL,
      platform ENUM('tiktok','instagram','unknown') NOT NULL,
      description TEXT NULL,
      transcript MEDIUMTEXT NULL,
      analysis_json JSON NOT NULL,
      thumbnail LONGBLOB NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  `);

  // folders table
  await db.execute(`
    CREATE TABLE IF NOT EXISTS folders (
      id BIGINT AUTO_INCREMENT PRIMARY KEY,
      created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      name VARCHAR(255) NOT NULL UNIQUE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  `);

  // Add title column to recipes if missing
  try {
    await db.execute(`ALTER TABLE recipes ADD COLUMN title VARCHAR(255) NULL AFTER created_at`);
  } catch {}

  // Add folder_id column to recipes if missing
  try {
    await db.execute(`ALTER TABLE recipes ADD COLUMN folder_id BIGINT NULL AFTER title`);
  } catch {}
  try {
    await db.execute(`ALTER TABLE recipes ADD CONSTRAINT fk_recipes_folder FOREIGN KEY (folder_id) REFERENCES folders(id) ON DELETE SET NULL`);
  } catch {}
}


