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

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-stock] Reading Stock file from local storage...');
        // Try multiple possible paths to be robust
        const pathsToTry = [
            path.join(process.cwd(), 'Item Availability.xlsx'),
            path.join(process.cwd(), 'public', 'Item Availability.xlsx'),
            path.join('/Users/christianvidalwolf/github/CrazeAnalytix', 'Item Availability.xlsx')
        ];

        let buffer = null;
        let foundPath = '';

        for (const p of pathsToTry) {
            console.log(`[fetch-stock] Checking path: ${p}`);
            if (fs.existsSync(p)) {
                buffer = fs.readFileSync(p);
                foundPath = p;
                break;
            }
        }

        if (!buffer) {
            throw new Error(`Stock file 'Item Availability.xlsx' not found in any of: ${pathsToTry.join(', ')}`);
        }

        console.log(`[fetch-stock] Successfully read Stock Excel from ${foundPath}, size: ${buffer.byteLength}`);

        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        res.status(200).send(buffer);
    } catch (error: any) {
        console.error('[fetch-stock] Error:', error);
        res.status(500).json({ error: error.message });
    }
}
