const axios = require('axios');

const ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ';
const BASE_URL = 'https://yuanqfswhberkoevtmfr.supabase.co';

(async () => {
  try {
    console.log('🔐 Fazendo login como admin...');
    const loginRes = await axios.post(`${BASE_URL}/auth/v1/token?grant_type=password`, {
      email: 'riseup@popcode.com.br',
      password: 'riseup'
    }, {
      headers: {
        'Content-Type': 'application/json',
        'apikey': ANON_KEY
      }
    });
    
    console.log('✅ Login admin bem-sucedido!\n');
    const token = loginRes.data.access_token;

    console.log('🔍 Buscando usuário fernando na tabela profiles...');
    const profilesRes = await axios.get(`${BASE_URL}/rest/v1/profiles?select=*`, {
      headers: {
        'apikey': ANON_KEY,
        'Authorization': `Bearer ${token}`
      }
    });

    console.log(`📊 Total de profiles: ${profilesRes.data.length}\n`);

    const fernandoProfile = profilesRes.data.find(u => 
      u.email && (
        u.email.toLowerCase().includes('fernando') ||
        u.full_name?.toLowerCase().includes('fernando')
      )
    );

    if (fernandoProfile) {
      console.log('✅ Fernando encontrado na tabela profiles:');
      console.log(JSON.stringify(fernandoProfile, null, 2));
    } else {
      console.log('❌ Fernando NÃO encontrado na tabela profiles\n');
    }

    // Buscar nos pacientes também
    console.log('\n🔍 Buscando fernando na tabela patients...');
    const patientsRes = await axios.get(`${BASE_URL}/rest/v1/patients?select=*`, {
      headers: {
        'apikey': ANON_KEY,
        'Authorization': `Bearer ${token}`
      }
    });

    console.log(`📊 Total de patients: ${patientsRes.data.length}\n`);

    const fernandoPatient = patientsRes.data.find(p => 
      p.email && (
        p.email.toLowerCase().includes('fernando') ||
        p.full_name?.toLowerCase().includes('fernando')
      )
    );

    if (fernandoPatient) {
      console.log('✅ Fernando encontrado na tabela patients:');
      console.log(JSON.stringify(fernandoPatient, null, 2));
    } else {
      console.log('❌ Fernando NÃO encontrado na tabela patients\n');
    }

    // Listar alguns emails para referência
    if (!fernandoProfile && !fernandoPatient) {
      console.log('\n📧 Alguns emails cadastrados nos profiles:');
      profilesRes.data.slice(0, 10).forEach((u, i) => {
        if (u.email) console.log(`  ${i+1}. ${u.email} - ${u.full_name || 'sem nome'}`);
      });
    }

  } catch (err) {
    console.error('❌ Erro:', err.response?.data || err.message);
    if (err.response) {
      console.error('Status:', err.response.status);
      console.error('Headers:', err.response.headers);
    }
  }
})();
