/**
 * Netlify Function to fetch Google Sheets data securely
 * Credentials are stored as environment variables, not exposed to frontend
 */

exports.handler = async (event) => {
    try {
        // Read credentials from environment variables (set in Netlify UI)
        const sheetId = process.env.GOOGLE_SHEET_ID;
        const sheetPassword = process.env.GOOGLE_SHEET_PASSWORD; // If needed for authentication
        
        if (!sheetId) {
            return {
                statusCode: 500,
                body: JSON.stringify({ error: 'GOOGLE_SHEET_ID not configured' })
            };
        }
        
        // Construct the export URL
        const csvUrl = `https://docs.google.com/spreadsheets/d/${sheetId}/export?format=csv`;
        
        // Fetch the CSV from Google Sheets
        const response = await fetch(csvUrl);
        
        if (!response.ok) {
            return {
                statusCode: response.status,
                body: JSON.stringify({ error: `Google Sheets returned ${response.status}` })
            };
        }
        
        const csv = await response.text();
        
        return {
            statusCode: 200,
            headers: {
                'Content-Type': 'text/csv',
                'Cache-Control': 'max-age=300' // Cache for 5 minutes
            },
            body: csv
        };
    } catch (error) {
        console.error('Error fetching Google Sheet:', error);
        return {
            statusCode: 500,
            body: JSON.stringify({ 
                error: 'Failed to fetch data',
                message: error.message 
            })
        };
    }
};
