const fs = require('fs');
const path = require('path');
const { createClient } = require('@supabase/supabase-js');

const envPath = path.resolve(__dirname, '../.env.local');

console.log('Reading env from:', envPath);

try {
    const envContent = fs.readFileSync(envPath, 'utf8');
    const envVars = {};
    envContent.split('\n').forEach(line => {
        const parts = line.split('=');
        if (parts.length >= 2) {
            const key = parts[0].trim();
            const value = parts.slice(1).join('=').trim().replace(/"/g, '');
            envVars[key] = value;
        }
    });

    const supabaseUrl = envVars['NEXT_PUBLIC_SUPABASE_URL'];
    const supabaseKey = envVars['NEXT_PUBLIC_SUPABASE_ANON_KEY'];

    if (!supabaseUrl || !supabaseKey) {
        console.error('❌ Missing Supabase Environment Variables in .env.local');
        console.log('URL:', supabaseUrl ? 'Set' : 'Missing');
        console.log('Key:', supabaseKey ? 'Set' : 'Missing');
        process.exit(1);
    }

    console.log('Checking connection to:', supabaseUrl);
    const supabase = createClient(supabaseUrl, supabaseKey);

    (async () => {
        try {
            const { error } = await supabase.auth.getSession();
            if (error) {
                console.error('❌ Connection Failed:', error.message);
                process.exit(1);
            } else {
                console.log('✅ Connection Successful! Supabase is reachable and keys are valid.');
            }
        } catch (err) {
            console.error('❌ Unexpected Error:', err);
        }
    })();

} catch (err) {
    console.error('❌ Could not read .env.local:', err.message);
}
