import { createClient } from '@supabase/supabase-js';
import * as dotenv from 'dotenv';
import path from 'path';

dotenv.config({ path: path.resolve(process.cwd(), '.env') });
const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_KEY!);

async function checkSchema() {
    console.log('--- Checking Table Schema ---');

    // We can use RPC to get table info, or just fetch one row
    const { data: orderRow, error: orderErr } = await supabase.from('orders').select('*').limit(1);
    if (!orderErr && orderRow && orderRow.length > 0) {
        console.log('Orders Columns:', Object.keys(orderRow[0]));
    } else {
        console.log('Orders error or no rows:', orderErr?.message);
    }

    const { data: historyRow, error: historyErr } = await supabase.from('trade_history').select('*').limit(1);
    if (!historyErr && historyRow && historyRow.length > 0) {
        console.log('History Columns:', Object.keys(historyRow[0]));
    } else {
        console.log('History error or no rows:', historyErr?.message);
    }
}

async function countByUser() {
    const userId = '8d5efd9e-0760-4859-8c07-0930ab3ede5a';
    console.log(`\n--- Counting for user ${userId} ---`);

    const { count: orderCount } = await supabase.from('orders').select('*', { count: 'exact', head: true }).eq('user_id', userId);
    const { count: historyCount } = await supabase.from('trade_history').select('*', { count: 'exact', head: true }).eq('user_id', userId);

    console.log(`Orders: ${orderCount}`);
    console.log(`History: ${historyCount}`);

    // Also check for 'global'
    const { count: globalOrderCount } = await supabase.from('orders').select('*', { count: 'exact', head: true }).eq('user_id', 'global');
    console.log(`Global Orders: ${globalOrderCount}`);
}

async function main() {
    await checkSchema();
    await countByUser();
}

main();
