const mysql = require('mysql2/promise');
require('dotenv').config();
const fs = require('fs');

const NODE_ENV = process.env.NODE_ENV || 'development';

let dbConfig;
if (NODE_ENV === 'development') {
  dbConfig = {
    host: process.env.DEV_DB_HOST || 'localhost',
    port: Number(process.env.DEV_DB_PORT) || 3306,
    user: process.env.DEV_DB_USER || 'root',
    password: process.env.DEV_DB_PASSWORD || '',
    database: process.env.DEV_DB_NAME || 'profitplanet_centralserver',
    ssl: undefined // No SSL for XAMPP/local
  };
} else {
  const getSSLConfig = () => {
    const useSSL = String(process.env.DB_SSL || '').toLowerCase() === 'true';
    const caPath = process.env.DB_SSL_CA_PATH;
    if (!useSSL) return undefined;
    if (caPath && fs.existsSync(caPath)) {
      return { ca: fs.readFileSync(caPath) };
    }
    return {}; // fallback SSL without CA if path missing
  };
  dbConfig = {
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT) || 3306,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    ssl: getSSLConfig()
  };
}

const REQUIRED_PERMISSIONS = [
  {
    name: 'can_create_referrals',
    description: 'User can create referral links',
    is_active: true
  },
  {
    name: 'can_subscribe',
    description: 'User can complete a subscription',
    is_active: true
  }
];

async function ensurePermissions() {
  const conn = await mysql.createConnection(dbConfig);
  try {
    for (const perm of REQUIRED_PERMISSIONS) {
      const [rows] = await conn.query(
        'SELECT id FROM permissions WHERE name = ?',
        [perm.name]
      );
      if (rows.length === 0) {
        await conn.query(
          'INSERT INTO permissions (name, description, is_active) VALUES (?, ?, ?)',
          [perm.name, perm.description, perm.is_active]
        );
        console.log(`✅ Permission "${perm.name}" created.`);
      } else {
        console.log(`ℹ️  Permission "${perm.name}" already exists.`);
      }
    }
    await conn.end();
    console.log('🎉 Permission initialization complete.');
  } catch (err) {
    console.error('💥 Error initializing permissions:', err);
    await conn.end();
    process.exit(1);
  }
}

module.exports = ensurePermissions;
