import axios from 'axios';
import pool from '../src/lib/db.js';
import dotenv from 'dotenv';
dotenv.config({ path: '../.env' });

const YOUTUBE_API_KEY = process.env.YOUTUBE_API_KEY;
const YOUTUBE_API_BASEUrl = 'https://www.googleapis.com/youtube/v3';

if (!YOUTUBE_API_KEY || YOUTUBE_API_KEY === 'your_youtube_v3_api_key_here') {
    console.error("YOUTUBE_API_KEY is not set. Please add it to your .env file.");
    process.exit(1);
}

/**
 * Update daily stats for all currently tracked channels in the database
 */
async function updateDailyStats() {
    console.log('Starting daily channel stats update...');
    try {
        // 1. Get all tracked channel IDs
        const [channels] = await pool.query('SELECT id FROM channels');

        if (channels.length === 0) {
            console.log('No channels currently tracked.');
            return;
        }

        // Process channels in batches of 50 (YouTube API limit)
        const channelIds = channels.map((row) => row.id);
        const dateToday = new Date().toISOString().split('T')[0];

        for (let i = 0; i < channelIds.length; i += 50) {
            const batchIds = channelIds.slice(i, i + 50).join(',');

            const response = await axios.get(`${YOUTUBE_API_BASEUrl}/channels`, {
                params: {
                    part: 'statistics',
                    id: batchIds,
                    key: YOUTUBE_API_KEY,
                },
            });

            const items = response.data.items;
            if (!items) continue;

            for (const item of items) {
                // Insert daily snapshot
                await pool.query(
                    `INSERT INTO channel_stats (channel_id, date, viewCount, subscriberCount, videoCount) 
           VALUES (?, ?, ?, ?, ?)
           ON DUPLICATE KEY UPDATE 
           viewCount = VALUES(viewCount), 
           subscriberCount = VALUES(subscriberCount), 
           videoCount = VALUES(videoCount)`,
                    [
                        item.id,
                        dateToday,
                        parseInt(item.statistics.viewCount, 10),
                        parseInt(item.statistics.subscriberCount, 10) || 0,
                        parseInt(item.statistics.videoCount, 10) || 0
                    ]
                );
            }

            console.log(`Updated batch ${i / 50 + 1} of stats.`);
        }

        console.log('Daily stats update completed successfully.');
    } catch (error) {
        console.error('Error updating channel stats:', error?.response?.data || error.message);
    } finally {
        await pool.end();
    }
}

updateDailyStats();
