require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.SUPABASE_SERVICE_KEY
);

const EXPECTED_TABLES = ['users', 'picks', 'scan_sessions', 'bets', 'outcomes', 'performance'];

async function verifySchema() {
  console.log('[VYNDR] Verifying database schema...\n');

  let allPassed = true;

  // Check each table exists by querying it
  for (const table of EXPECTED_TABLES) {
    const { data, error } = await supabase.from(table).select('*').limit(0);
    if (error) {
      console.error(`  FAIL: ${table} — ${error.message}`);
      allPassed = false;
    } else {
      console.log(`  OK: ${table}`);
    }
  }

  console.log('');

  // Test RLS: service role should be able to query all tables
  console.log('Testing service role access...');
  for (const table of EXPECTED_TABLES) {
    const { error } = await supabase.from(table).select('*').limit(1);
    if (error) {
      console.error(`  FAIL: service role cannot access ${table} — ${error.message}`);
      allPassed = false;
    } else {
      console.log(`  OK: service role can access ${table}`);
    }
  }

  console.log('');

  if (allPassed) {
    console.log('ALL CHECKS PASSED. Schema is correctly applied.');
  } else {
    console.error('SOME CHECKS FAILED. Review errors above.');
    process.exit(1);
  }
}

verifySchema().catch((err) => {
  console.error('Verification failed:', err.message);
  process.exit(1);
});
