/**
 * Loopuman Core Tests
 * Run: node tests/core.test.js
 */
'use strict';
require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

let passed = 0, failed = 0;

async function test(name, fn) {
  try {
    await fn();
    console.log(`✅ ${name}`);
    passed++;
  } catch (e) {
    console.log(`❌ ${name}: ${e.message}`);
    failed++;
  }
}

function assert(condition, msg) {
  if (!condition) throw new Error(msg || 'Assertion failed');
}

async function runTests() {
  console.log('\n🧪 LOOPUMAN CORE TESTS\n');

  // Database Tests
  await test('Database: app_users accessible', async () => {
    const { error } = await supabase.from('app_users').select('id').limit(1);
    assert(!error, error?.message);
  });

  await test('Database: tasks accessible', async () => {
    const { error } = await supabase.from('tasks').select('id').limit(1);
    assert(!error, error?.message);
  });

  await test('Database: submissions accessible', async () => {
    const { error } = await supabase.from('submissions').select('id').limit(1);
    assert(!error, error?.message);
  });

  await test('Database: vae_balances accessible', async () => {
    const { error } = await supabase.from('vae_balances').select('user_id').limit(1);
    assert(!error, error?.message);
  });

  await test('Database: transactions accessible', async () => {
    const { error } = await supabase.from('transactions').select('id').limit(1);
    assert(!error, error?.message);
  });

  await test('Database: task_batches accessible', async () => {
    const { error } = await supabase.from('task_batches').select('id').limit(1);
    assert(!error, error?.message);
  });

  // Business Logic Tests
  await test('Commission: Worker gets 80%', () => {
    const budget = 100;
    const workerPay = Math.floor(budget * 0.8);
    assert(workerPay === 80, `Expected 80, got ${workerPay}`);
  });

  await test('Commission: Requester pays 120%', () => {
    const budget = 100;
    const requesterPay = Math.floor(budget * 1.2);
    assert(requesterPay === 120, `Expected 120, got ${requesterPay}`);
  });

  await test('Trust Score: Starts at 30', () => {
    const defaultTrust = 30;
    assert(defaultTrust === 30);
  });

  await test('Negative balance prevention', () => {
    const balance = 10;
    const withdrawal = 50;
    const result = Math.max(0, balance - withdrawal);
    assert(result === 0, 'Should not go negative');
  });

  // Environment Tests
  await test('Environment: SUPABASE_URL set', () => {
    assert(process.env.SUPABASE_URL, 'SUPABASE_URL not set');
  });

  await test('Environment: BOT_TOKEN set', () => {
    assert(process.env.BOT_TOKEN, 'BOT_TOKEN not set');
  });

  await test('Environment: TREASURY_ADDRESS set', () => {
    assert(process.env.TREASURY_ADDRESS, 'TREASURY_ADDRESS not set');
  });

  // API Tests
  await test('Enterprise API: Health check', async () => {
    const http = require('http');
    const result = await new Promise((resolve) => {
      http.get('http://localhost:3001/health', (res) => {
        let data = '';
        res.on('data', c => data += c);
        res.on('end', () => resolve(JSON.parse(data)));
      }).on('error', () => resolve(null));
    });
    assert(result?.status === 'ok', 'API not responding');
  });

  // Summary
  console.log(`\n━━━━━━━━━━━━━━━━━━━━━━`);
  console.log(`✅ Passed: ${passed}`);
  console.log(`❌ Failed: ${failed}`);
  console.log(`━━━━━━━━━━━━━━━━━━━━━━\n`);
  
  process.exit(failed > 0 ? 1 : 0);
}

runTests();
