
const Database = require('better-sqlite3');
const path = require('path');
const bcrypt = require('bcryptjs');

const dbPath = path.resolve(__dirname, 'dashboard.db');
const db = new Database(dbPath);

// Initialize tables
db.exec(`
    CREATE TABLE IF NOT EXISTS admin_users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE NOT NULL,
        password_hash TEXT NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );

    CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );
`);

// Seed default admin if none exists
const adminCount = db.prepare('SELECT COUNT(*) as count FROM admin_users').get().count;
if (adminCount === 0) {
    const defaultPassword = 'admin'; // User should change this immediately
    const hash = bcrypt.hashSync(defaultPassword, 10);
    db.prepare('INSERT INTO admin_users (username, password_hash) VALUES (?, ?)').run('admin', hash);
    console.log('Default admin user created: admin / admin');
}

// Seed default settings if none exist
const seedSettings = (key, defaultValue) => {
    const exists = db.prepare('SELECT 1 FROM settings WHERE key = ?').get(key);
    if (!exists) {
        db.prepare('INSERT INTO settings (key, value) VALUES (?, ?)').run(key, JSON.stringify(defaultValue));
    }
};

seedSettings('whmcs_api', {
    url: '',
    identifier: '',
    secret: ''
});

seedSettings('smtp_config', {
    host: '',
    port: 587,
    user: '',
    pass: '',
    fromEmail: ''
});

seedSettings('product_ids', {
    vps: [],
    dedicated: [],
    colocation: [],
    hosting: []
});

seedSettings('uddoktapay_config', {
    api_url: 'https://sandbox.uddoktapay.com/',
    api_key: '982d381360a69d419689740d9f2e26ce36fb7a50'
});

seedSettings('branding', {
    appName: 'CloudCore',
    appLogo: 'https://cdn-icons-png.flaticon.com/512/5968/5968204.png',
    footerText: '© 2026 CloudCore. All rights reserved.',
    loginTitle: 'Welcome Back',
    loginSubtitle: 'Manage your cloud infrastructure with ease.'
});

seedSettings('virtualizor_servers', {
    // Format: { serverId: { ip, key, pass } }
    3: {
        ip: '160.187.130.18',
        key: 'EfBT3awH4We7tLIIGX0aCVFIkVtcrBdu',
        pass: 'uISl7gOvBjKnMNNZrOKwg3ugk4rzo9Ba'
    }
});

module.exports = db;
