const { exec } = require('child_process');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

async function downloadVideo(searchQuery) {
    const tempFilePath = path.join(__dirname, 'tmp', `${uuidv4()}.mp3`);

    const ytDlpArgs = [
        '--cookies', path.join(__dirname, '../cookies.txt'),
        '--format', 'bestaudio',
        '--output', tempFilePath,
        searchQuery,
    ];

    return new Promise((resolve, reject) => {
        exec(`yt-dlp ${ytDlpArgs.join(' ')}`, (error, stdout, stderr) => {
            if (error) {
                console.error('yt-dlp error:', stderr);
                return reject(new Error('Failed to download video with yt-dlp'));
            }
            resolve(tempFilePath);
        });
    });
}

module.exports = { downloadVideo };