import type { VercelRequest, VercelResponse } from '@vercel/node';

const DROPBOX_URL = "https://www.dropbox.com/scl/fi/b9zxn4z5i7sxwfakk5g5y/Amazon-Sell-Out-2023-2025.csv?rlkey=uoto6v0mm99py8nszy8ldtez8&st=pzn1zkrg&dl=1";

export default async function handler(req: VercelRequest, res: VercelResponse) {
    // CORS headers
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    if (req.method === 'OPTIONS') {
        return res.status(200).end();
    }

    try {
        console.log('[fetch-data] Fetching from Dropbox...');
        const response = await fetch(DROPBOX_URL, {
            cache: 'no-store',
            headers: {
                'Pragma': 'no-cache',
                'Cache-Control': 'no-cache'
            }
        });

        if (!response.ok) {
            throw new Error(`Dropbox responded with ${response.status}`);
        }

        const csvData = await response.text();
        console.log('[fetch-data] Successfully fetched CSV, size:', csvData.length);

        res.setHeader('Content-Type', 'text/csv');
        res.status(200).send(csvData);
    } catch (error: any) {
        console.error('[fetch-data] Error:', error);
        res.status(500).json({ error: error.message });
    }
}
