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);
        }

        // 3. users table
        const createUsersSql = `
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                login_id VARCHAR(50) UNIQUE NOT NULL,
                password VARCHAR(255) NOT NULL,
                name VARCHAR(100),
                role VARCHAR(20) DEFAULT 'admin',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        `;
        await connection.query(createUsersSql);

        // Seed Initial Admin
        const bcrypt = require('bcryptjs');
        const adminId = 'admin';
        const adminPw = '^Ocean1472bk';
        const [existing] = await connection.query('SELECT id FROM users WHERE login_id = ?', [adminId]);

        if (existing.length === 0) {
            const hashedPw = await bcrypt.hash(adminPw, 10);
            await connection.query(
                'INSERT INTO users (login_id, password, name, role) VALUES (?, ?, ?, ?)',
                [adminId, hashedPw, 'Administrator', 'admin']
            );
            console.log('✅ Created initial admin account');
        }

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

init();
