const assert = require('assert');
const path = require('path');
const express = require('express');
const superAdminRoutes = require('../src/routes/superadmin.routes');
const controller = require('../src/controllers/superadmin.controller');
const SupabaseSuperAdminService = require('../src/services/SupabaseSuperAdminService');

console.log('🧪 Starting SuperAdmin License Flow & Controller Unit Tests...');

async function runTests() {
  // Test 1: Verify SupabaseSuperAdminService status & initialization
  const status = await SupabaseSuperAdminService.getStatus();
  assert(typeof status.configured === 'boolean', 'status.configured should be boolean');
  assert(typeof status.canConnect === 'boolean', 'status.canConnect should be boolean');
  console.log('✓ SupabaseSuperAdminService status check passed');

  // Test 2: Mock express req/res for getMetrics
  let metricsResult = null;
  const mockResMetrics = {
    json: (data) => { metricsResult = data; return mockResMetrics; },
    status: (code) => mockResMetrics
  };

  await controller.getMetrics({}, mockResMetrics);
  assert(metricsResult !== null, 'getMetrics should return data');
  assert(metricsResult.supabase_sync !== undefined, 'getMetrics should include supabase_sync metrics');
  assert(typeof metricsResult.supabase_sync.status_label === 'string', 'status_label should be a string');
  console.log('✓ controller.getMetrics surfaces supabase_sync metrics correctly:', metricsResult.supabase_sync);

  // Test 3: Mock express req/res for listTenants
  let tenantsResult = null;
  const mockResTenants = {
    json: (data) => { tenantsResult = data; return mockResTenants; },
    status: (code) => mockResTenants
  };

  await controller.listTenants({}, mockResTenants);
  assert(Array.isArray(tenantsResult), 'listTenants should return an array');
  if (tenantsResult.length > 0) {
    const first = tenantsResult[0];
    assert(first.supabase_status !== undefined, 'tenant should surface supabase_status');
    assert(typeof first.supabase_synced === 'boolean', 'tenant should surface boolean supabase_synced');
    console.log(`✓ controller.listTenants returned ${tenantsResult.length} tenants with live Supabase status (first tenant status: ${first.supabase_status})`);

    // Test 4: Inspect specific tenant endpoint controller
    let inspectResult = null;
    const mockReqInspect = { params: { id: first.id } };
    const mockResInspect = {
      json: (data) => { inspectResult = data; return mockResInspect; },
      status: (code) => mockResInspect
    };

    await controller.inspectTenantSupabase(mockReqInspect, mockResInspect);
    assert(inspectResult !== null, 'inspectTenantSupabase should return data');
    assert(inspectResult.ok === true, 'inspectTenantSupabase should return ok: true');
    assert(inspectResult.local !== undefined, 'inspectTenantSupabase should include local tenant state');
    console.log(`✓ controller.inspectTenantSupabase passed for tenant ${first.id} (status: ${inspectResult.supabase_status})`);
  }

  console.log('\n🎉 ALL SUPERADMIN CONTROLLER & SUPABASE LICENSE FLOW TESTS PASSED SUCCESSFULLY!\n');
}

runTests().catch(err => {
  console.error('❌ Test execution failed:', err);
  process.exit(1);
});
