import assert from 'node:assert/strict';
import http from 'node:http';
import { runRemoteAuthSmoke } from './remote-auth-jwt-smoke.js';

const tenantId = '00000000-0000-0000-0000-000000000001';
const wrongTenantId = '00000000-0000-0000-0000-000000000901';

function json(res, status, payload) {
  res.writeHead(status, { 'content-type': 'application/json' });
  res.end(JSON.stringify(payload));
}

function bearer(req) {
  const header = req.headers.authorization || '';
  return header.replace(/^Bearer\s+/i, '').trim();
}

function isWrongTenant(req) {
  return req.headers['x-tenant-id'] === wrongTenantId;
}

const server = http.createServer((req, res) => {
  const token = bearer(req);
  const url = new URL(req.url || '/', 'http://127.0.0.1');

  if (token === 'invalid.jwt.token') {
    json(res, 401, { code: 'AUTH_SESSION_INVALID' });
    return;
  }

  if (isWrongTenant(req) && url.pathname === '/api/profile/me') {
    json(res, 401, { code: 'AUTH_SESSION_INVALID' });
    return;
  }

  if (token === 'student-token') {
    if (url.pathname === '/api/auth/me') {
      json(res, 200, { user: { id: 'student-user' }, session: { source: 'supabase_jwt' } });
      return;
    }
    if (url.pathname === '/api/profile/me') {
      json(res, 200, { item: { userId: 'student-user' } });
      return;
    }
    if (url.pathname === '/api/tenant-admin/overview') {
      json(res, 403, { code: 'TENANT_ADMIN_REQUIRED' });
      return;
    }
    if (url.pathname === '/api/platform-admin/overview') {
      json(res, 403, { code: 'PLATFORM_ADMIN_REQUIRED' });
      return;
    }
  }

  if (token === 'tenant-token') {
    if (url.pathname === '/api/auth/me') {
      json(res, 200, { user: { id: 'tenant-user' }, session: { source: 'supabase_jwt' } });
      return;
    }
    if (url.pathname === '/api/tenant-admin/overview') {
      json(res, 200, { item: { id: tenantId } });
      return;
    }
    if (url.pathname === '/api/platform-admin/overview') {
      json(res, 403, { code: 'PLATFORM_ADMIN_REQUIRED' });
      return;
    }
  }

  if (token === 'platform-token') {
    if (url.pathname === '/api/platform-admin/overview') {
      json(res, 200, { item: { tenants: { total: 2 } } });
      return;
    }
    if (url.pathname === '/api/auth/me') {
      json(res, 200, { user: { id: 'platform-user' }, session: { source: 'supabase_jwt' } });
      return;
    }
  }

  json(res, 404, { code: 'NOT_FOUND', path: url.pathname });
});

await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));

try {
  const address = server.address();
  const results = await runRemoteAuthSmoke(
    {
      apiBaseUrl: `http://127.0.0.1:${address.port}`,
      tenantId,
      wrongTenantId,
      timeoutMs: 5000,
      requireAdminTokens: true,
      student: {
        token: 'student-token',
        expectedUserId: 'student-user',
      },
      tenantAdmin: {
        token: 'tenant-token',
        expectedUserId: 'tenant-user',
      },
      platformAdmin: {
        token: 'platform-token',
        expectedUserId: 'platform-user',
        tenantId,
      },
    },
    { quiet: true },
  );

  assert.equal(results.some(item => item.name === 'student.auth_me.session_source' && item.status === 'pass'), true);
  assert.equal(results.some(item => item.name === 'student.tenant_admin_denied' && item.status === 'pass'), true);
  assert.equal(results.some(item => item.name === 'platform_admin.overview' && item.status === 'pass'), true);
  assert.equal(results.filter(item => item.status === 'fail').length, 0);
  console.log('[PASS] remote Auth/JWKS smoke script');
} finally {
  await new Promise(resolve => server.close(resolve));
}
