const BaseModel = require('./BaseModel');

class ServiceModel extends BaseModel {

    async saveMarketPrices(data) {
        await this.query(`TRUNCATE TABLE market_latest`);
        const now = Math.floor(Date.now() / 1000);
        for (const [key, item] of Object.entries(data)) {

            await this.query(
                `INSERT INTO market_latest
                (market_key, market_name, category, price, price_low, price_high, change_value, change_percent, source, update_time)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    market_name = VALUES(market_name),
                    category = VALUES(category),
                    price = VALUES(price),
                    price_low = VALUES(price_low),
                    price_high = VALUES(price_high),
                    change_value = VALUES(change_value),
                    change_percent = VALUES(change_percent),
                    update_time = VALUES(update_time)`,
    
                [
                    key,
                    item.name || null,
                    item.type || null,
                    this.normalizePrice(item.price) || null,
                    this.normalizePrice(item.low) || null,
                    this.normalizePrice(item.high) || null,
                    this.normalizePrice(item.changeValue) || null,
                    this.normalizePrice(item.changePercent) || null,
                    'tgju',
                    now
                ]
            );
        }
    }
    
    async getPricesByKeys(importantKeys) {
        // لیست کلیدهای ارزهای مهم که می‌خواهیم در گزارش عمومی نمایش دهیم
        //const importantKeys = ['price_dollar_rl', 'price_eur', 'price_ae', 'price_gbp', 'price_tr'];
        
        // تبدیل آرایه به فرمت مناسب برای کوئری SQL
        const placeholders = importantKeys.map(() => '?').join(',');
        
        const rows = await this.query(
            `SELECT market_key, market_name, price, change_percent 
             FROM market_latest 
             WHERE market_key IN (${placeholders}) ORDER BY id ASC`,
            importantKeys
        );
        
        return rows;
    }
    
    
}

module.exports = new ServiceModel();