import assert from 'node:assert/strict';
import { pathToFileURL } from 'node:url';

const repoRoot = process.cwd();
const authModule = await import(pathToFileURL(`${repoRoot}/apps/taro/src/services/api-auth.ts`).href);

authModule.setSupabaseAccessTokenProviderForTest(async () => 'supabase_access_token');

assert.equal(
  await authModule.resolveApiAuthorization({
    hasTokenOverride: false,
    legacyToken: 'tk_legacy_token',
  }),
  'supabase_access_token',
);

assert.equal(
  await authModule.resolveApiAuthorization({
    authMode: 'none',
    hasTokenOverride: false,
    legacyToken: 'tk_legacy_token',
  }),
  null,
);

assert.equal(
  await authModule.resolveApiAuthorization({
    authMode: 'legacy',
    hasTokenOverride: false,
    legacyToken: 'tk_legacy_token',
  }),
  'tk_legacy_token',
);

assert.equal(
  await authModule.resolveApiAuthorization({
    hasTokenOverride: true,
    explicitToken: null,
    legacyToken: 'tk_legacy_token',
  }),
  null,
);

authModule.setSupabaseAccessTokenProviderForTest(async () => null);

assert.equal(
  await authModule.resolveApiAuthorization({
    hasTokenOverride: false,
    legacyToken: 'tk_legacy_token',
  }),
  'tk_legacy_token',
);

assert.equal(
  await authModule.resolveApiAuthorization({
    authMode: 'supabase',
    hasTokenOverride: false,
    legacyToken: 'tk_legacy_token',
  }),
  null,
);

const authenticatedHeaders = authModule.buildApiHeaders({
  tenantId: 'tenant-1',
  token: 'supabase_access_token',
  extraHeaders: { 'x-client-version': 'test' },
});
assert.equal(authenticatedHeaders.authorization, 'Bearer supabase_access_token');
assert.equal(authenticatedHeaders['x-tenant-id'], 'tenant-1');
assert.equal(authenticatedHeaders['x-client-version'], 'test');

const publicHeaders = authModule.buildApiHeaders({ tenantId: null, token: null });
assert.equal(publicHeaders.authorization, undefined);
assert.equal(publicHeaders['x-tenant-id'], undefined);

assert.throws(
  () => authModule.buildApiHeaders({ extraHeaders: { Authorization: 'Bearer unsafe' } }),
  /Reserved API header cannot be overridden/,
);
assert.throws(
  () => authModule.buildApiHeaders({ tenantId: 'tenant-1', extraHeaders: { 'X-Tenant-Id': 'tenant-2' } }),
  /Reserved API header cannot be overridden/,
);

authModule.setSupabaseAccessTokenProviderForTest(null);

console.log('[PASS] Taro API auth mode guardrails');
