/* eslint-disable */
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL || 'postgresql://jumpa_admin:JumpaS3cur3%21%40%23@xcom-ultra-alpha.ultramodul.xyz:5432/jumpadb'
});

async function migrate() {
  try {
    console.log("Memulai migrasi arsitektur Omni-Dashboard JUMPA.ID...");

    // Tabel platform_settings (White Label)
    await pool.query(`
      CREATE TABLE IF NOT EXISTS platform_settings (
        id SERIAL PRIMARY KEY,
        key VARCHAR(255) UNIQUE NOT NULL,
        value TEXT NOT NULL
      )
    `);
    
    // Injeksi nama default jika belum ada
    await pool.query(`
      INSERT INTO platform_settings (key, value) 
      VALUES ('platform_name', 'JUMPA.ID') 
      ON CONFLICT (key) DO NOTHING
    `);

    // Tabel billing_packages
    await pool.query(`
      CREATE TABLE IF NOT EXISTS billing_packages (
        id SERIAL PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        max_users INTEGER NOT NULL,
        max_rooms INTEGER NOT NULL,
        price_monthly DECIMAL(10, 2) NOT NULL
      )
    `);

    // Injeksi paket dasar
    await pool.query(`
      INSERT INTO billing_packages (id, name, max_users, max_rooms, price_monthly) 
      VALUES 
        (1, 'Basic Plan (BETA)', 100, 5, 0),
        (2, 'Pro Plan', 1000, 50, 500000),
        (3, 'Enterprise Plan', 10000, 500, 2000000)
      ON CONFLICT (id) DO NOTHING
    `);

    // Menambah kolom billing ke tabel tenants jika belum ada
    await pool.query(`
      ALTER TABLE tenants 
      ADD COLUMN IF NOT EXISTS package_id INTEGER REFERENCES billing_packages(id) DEFAULT 1,
      ADD COLUMN IF NOT EXISTS billing_status VARCHAR(50) DEFAULT 'ACTIVE',
      ADD COLUMN IF NOT EXISTS billing_expiry TIMESTAMP
    `);

    console.log("✅ Migrasi TSM berhasil 100%!");
    process.exit(0);
  } catch (err) {
    console.error("❌ Gagal migrasi:", err);
    process.exit(1);
  }
}

migrate();

