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

async function init() {
    const connection = await mysql.createConnection({
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        port: process.env.DB_PORT || 3307  // Using 3307 as per .env
    });

    try {
        const dbName = 'smart_ims_license_db';
        await connection.query(`CREATE DATABASE IF NOT EXISTS ${dbName}`);
        await connection.query(`USE ${dbName}`);

        // 1. issued_licenses
        const createTableSql = `
            CREATE TABLE IF NOT EXISTS issued_licenses (
                id INT AUTO_INCREMENT PRIMARY KEY,
                module_code VARCHAR(50) NOT NULL,
                license_key TEXT NOT NULL,
                license_type VARCHAR(20) NOT NULL,
                subscriber_id VARCHAR(100) NOT NULL,
                status VARCHAR(20) DEFAULT 'ISSUED',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        `;
        await connection.query(createTableSql);

        try {
            await connection.query(`
                INSERT IGNORE INTO smart_ims_license_db.issued_licenses 
                (module_code, license_key, license_type, subscriber_id, status, created_at)
                SELECT module_code, license_key, license_type, subscriber_id, status, created_at 
                FROM sokuree_platform_dev.issued_licenses;
            `);
            console.log('✅ Migrated issued_licenses');
        } catch (e) {
            console.log('Skip issued_licenses migration:', e.message);
        }

        // 2. license_history
        const createHistorySql = `
            CREATE TABLE IF NOT EXISTS license_history (
                id INT AUTO_INCREMENT PRIMARY KEY,
                module_code VARCHAR(50) NOT NULL,
                license_key TEXT,
                license_type VARCHAR(20),
                subscriber_id VARCHAR(50),
                activated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        `;
        await connection.query(createHistorySql);

        try {
            await connection.query(`
                INSERT IGNORE INTO smart_ims_license_db.license_history 
                (module_code, license_key, license_type, subscriber_id, activated_at)
                SELECT module_code, license_key, license_type, subscriber_id, activated_at 
                FROM sokuree_platform_dev.license_history;
            `);
            console.log('✅ Migrated license_history');
        } catch (e) {
            console.log('Skip license_history migration:', e.message);
        }

    } catch (err) {
        console.error('FAILED:', err);
    } finally {
        await connection.end();
    }
}

init();
