// handlers/pricingHandler.js
const fs = require('fs').promises;
const path = require('path');
const { ALLOWED_SIZES } = require('../config/predefinedOptions');

const pricingDbPath = path.join(__dirname, '..', 'database_harga.json');
const userState = {};

/**
 * Reads the pricing database.
 * @returns {Promise<Object>} The pricing data.
 */
async function readPricingDb() {
    try {
        const data = await fs.readFile(pricingDbPath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        if (error.code === 'ENOENT') {
            console.log('File database_harga.json tidak ditemukan, akan dibuat dari default.');
            return null;
        }
        throw error;
    }
}

/**
 * Writes to the pricing database.
 * @param {Object} data The data to write.
 */
async function writePricingDb(data) {
    await fs.writeFile(pricingDbPath, JSON.stringify(data, null, 2), 'utf8');
}

/**
 * Initializes the pricing database if it doesn't exist.
 * Populates it with default values from predefinedOptions.js.
 */
async function initializePricingDb() {
    let pricingData = await readPricingDb();
    let needsUpdate = false;
    if (pricingData === null) {
        pricingData = {};
        needsUpdate = true;
    }

    // Check each size for initialization and 'enabled' flag
    ALLOWED_SIZES.forEach(size => {
        if (!pricingData[size.slug]) {
            pricingData[size.slug] = {
                price_min_idr: size.price_min_idr,
                price_max_idr: size.price_max_idr,
                enabled: true // Default to enabled
            };
            needsUpdate = true;
        } else if (pricingData[size.slug].enabled === undefined) {
            pricingData[size.slug].enabled = true; // Add flag if missing
            needsUpdate = true;
        }
    });

    if (needsUpdate) {
        await writePricingDb(pricingData);
        console.log('✅ File database_harga.json berhasil diinisialisasi/diperbarui.');
    }
}


/**
 * Shows the main product management menu for admins.
 */
function showProductMenu(bot, chatId) {
    const message = "<b>📦 Manajemen Produk</b>\n\nPilih aksi yang Anda inginkan:";
    bot.sendMessage(chatId, message, {
        parse_mode: 'HTML',
        reply_markup: {
            inline_keyboard: [
                [{ text: '🔧 Atur Harga Jual', callback_data: 'pricing_set_menu' }],
                [{ text: '📊 Atur Status Jual', callback_data: 'pricing_status_menu' }],
                [{ text: '📋 Lihat Semua Produk', callback_data: 'pricing_list' }]
            ]
        }
    });
}


/**
 * Displays the current prices and status for all available sizes.
 */
async function handleListPrices(bot, chatId) {
    const pricingData = await readPricingDb();
    let message = '📊 <b>Daftar Harga & Status Produk</b> 📊\n\n';

    for (const size of ALLOWED_SIZES) {
        const info = pricingData[size.slug];
        const displayText = `${size.memory / 1024}GB/${size.vcpus}vCPU`;
        message += `▪️ <b>${displayText}</b>\n`;
        if (info) {
            const statusIcon = info.enabled ? '✅ Aktif' : '❌ Nonaktif';
            message += `  ├ Status: ${statusIcon}\n`;
            message += `  ├ Min (1 hari): Rp ${info.price_min_idr.toLocaleString('id-ID')}\n`;
            message += `  └ Max (30 hari): Rp ${info.price_max_idr.toLocaleString('id-ID')}\n\n`;
        } else {
            message += `  └ Info harga tidak ditemukan.\n\n`;
        }
    }

    bot.sendMessage(chatId, message, {
        parse_mode: 'HTML',
        reply_markup: {
            inline_keyboard: [[{ text: '↩️ Kembali', callback_data: 'product_show_menu' }]]
        }
    });
}

/**
 * Shows a menu to select which size's price to set.
 */
async function handleSetPriceMenu(bot, chatId) {
    const keyboard = ALLOWED_SIZES.map(s => {
        const displayText = `${s.memory / 1024}GB/${s.vcpus}vCPU`;
        return [{ text: displayText, callback_data: `pricing_set_price_${s.slug}` }];
    });
    keyboard.push([{ text: '↩️ Kembali', callback_data: 'product_show_menu' }]);

    bot.sendMessage(chatId, '👇 Pilih ukuran yang harganya akan diatur:', {
        reply_markup: { inline_keyboard: keyboard }
    });
}

/**
 * Shows a menu to enable/disable sizes.
 */
async function handleSetStatusMenu(bot, chatId) {
    const pricingData = await readPricingDb();
    const keyboard = ALLOWED_SIZES.map(s => {
        const info = pricingData[s.slug];
        const statusIcon = info && info.enabled ? '✅' : '❌';
        const displayText = `${statusIcon} ${s.memory / 1024}GB/${s.vcpus}vCPU`;
        return [{ text: displayText, callback_data: `pricing_toggle_status_${s.slug}` }];
    });
    keyboard.push([{ text: '↩️ Kembali', callback_data: 'product_show_menu' }]);

    bot.sendMessage(chatId, '👇 Klik untuk mengubah status jual (Aktif/Nonaktif):', {
        reply_markup: { inline_keyboard: keyboard }
    });
}


async function handleTextMessage(bot, msg) {
    const chatId = msg.chat.id;
    if (!userState[chatId] || !userState[chatId].step.startsWith('pricing_')) return false;

    const state = userState[chatId];
    const text = msg.text;
    const price = parseInt(text, 10);

    if (isNaN(price) || price < 0) {
        bot.sendMessage(chatId, '⚠️ Harga tidak valid. Harap masukkan angka positif.');
        return true;
    }

    if (state.step === 'pricing_ask_min') {
        state.minPrice = price;
        state.step = 'pricing_ask_max';
        bot.sendMessage(chatId, `✅ Harga minimal diatur ke <b>Rp ${price.toLocaleString('id-ID')}</b>.\n\nSekarang, masukkan harga <b>MAKSIMAL</b> (untuk 30 hari):`, { parse_mode: 'HTML' });
    } else if (state.step === 'pricing_ask_max') {
        state.maxPrice = price;
        
        if (state.maxPrice <= state.minPrice) {
            bot.sendMessage(chatId, '⚠️ Harga maksimal harus lebih besar dari harga minimal. Silakan masukkan harga maksimal lagi.');
            return true;
        }

        const pricingData = await readPricingDb();
        // Ensure the entry exists before updating
        if (!pricingData[state.slug]) {
             pricingData[state.slug] = { enabled: true }; // Default enabled if it's a new entry
        }
        pricingData[state.slug].price_min_idr = state.minPrice;
        pricingData[state.slug].price_max_idr = state.maxPrice;


        await writePricingDb(pricingData);
        delete userState[chatId];
        
        const sizeDetails = ALLOWED_SIZES.find(s => s.slug === state.slug);
        const displayText = `${sizeDetails.memory / 1024}GB/${sizeDetails.vcpus}vCPU`;

        await bot.sendMessage(chatId, `✅ Harga untuk <b>${displayText}</b> berhasil diperbarui!`, { parse_mode: 'HTML' });
        setTimeout(() => showProductMenu(bot, chatId), 1500);
    }
    return true;
}

async function handleCallbackQuery(bot, cbq) {
    const data = cbq.data;
    const isProductCallback = data.startsWith('pricing_') || data.startsWith('product_');
    if (!isProductCallback) return false;

    const msg = cbq.message;
    const chatId = msg.chat.id;

    await bot.deleteMessage(chatId, msg.message_id).catch(() => {});

    if (data === 'product_show_menu') {
        showProductMenu(bot, chatId);
    } else if (data === 'pricing_list') {
        await handleListPrices(bot, chatId);
    } else if (data === 'pricing_set_menu') {
        await handleSetPriceMenu(bot, chatId);
    } else if (data === 'pricing_status_menu') {
        await handleSetStatusMenu(bot, chatId);
    } else if (data.startsWith('pricing_set_price_')) {
        const slug = data.replace('pricing_set_price_', '');
        userState[chatId] = { step: 'pricing_ask_min', slug: slug };
        const sizeDetails = ALLOWED_SIZES.find(s => s.slug === slug);
        const displayText = `${sizeDetails.memory / 1024}GB/${sizeDetails.vcpus}vCPU`;
        
        const pricingData = await readPricingDb();
        const currentPrice = pricingData[slug];
        
        let currentPriceText = "Saat ini: Harga belum diatur.";
        if (currentPrice && currentPrice.price_min_idr !== undefined && currentPrice.price_max_idr !== undefined) {
            currentPriceText = `Saat ini: Min Rp ${currentPrice.price_min_idr.toLocaleString('id-ID')}, Max Rp ${currentPrice.price_max_idr.toLocaleString('id-ID')}`;
        }

        bot.sendMessage(chatId, `Mengatur harga untuk <b>${displayText}</b>.\n${currentPriceText}\n\nMasukkan harga <b>MINIMAL</b> (untuk 1 hari):`, { parse_mode: 'HTML' });
    } else if (data.startsWith('pricing_toggle_status_')) {
        const slug = data.replace('pricing_toggle_status_', '');
        const pricingData = await readPricingDb();
        if (pricingData[slug]) {
            pricingData[slug].enabled = !pricingData[slug].enabled; // Flip the status
            await writePricingDb(pricingData);
        }
        await handleSetStatusMenu(bot, chatId); // Refresh the menu
    }

    return true;
}

module.exports = {
    initializePricingDb,
    readPricingDb,
    showProductMenu,
    handleTextMessage,
    handleCallbackQuery
};

