import './setup.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { load } from './setup.mjs';

const { isAllowedGraphHost, isAllowedAuthorityHost } = await load('../data/graphHosts.js');
const { graphConnectionSchema } = await load('../forms/schemas.js');

test('allow-list accepts Microsoft cloud hosts', () => {
  assert.ok(isAllowedGraphHost('https://graph.microsoft.com'));
  assert.ok(isAllowedGraphHost('https://graph.microsoft.us'));
  assert.ok(isAllowedAuthorityHost('https://login.microsoftonline.com'));
});

test('allow-list rejects non-Microsoft and internal hosts', () => {
  assert.ok(!isAllowedGraphHost('https://graph.microsoft.com.evil.com'));
  assert.ok(!isAllowedGraphHost('http://169.254.169.254'));
  assert.ok(!isAllowedAuthorityHost('https://internal.corp.local'));
  assert.ok(!isAllowedGraphHost('https://graph.microsoft.com:8080@evil.com'));
});

test('graph connection schema rejects SSRF endpoints', () => {
  const result = graphConnectionSchema.safeParse({
    name: 'Bad',
    tenantId: 'contoso',
    clientId: 'abc',
    clientSecret: 'shh',
    graphBaseUrl: 'http://169.254.169.254',
    authorityHost: 'https://login.microsoftonline.com'
  });
  assert.equal(result.success, false);
});

test('graph connection schema accepts a valid Microsoft endpoint', () => {
  const result = graphConnectionSchema.safeParse({
    name: 'Good',
    tenantId: 'contoso',
    clientId: 'abc',
    clientSecret: 'shh',
    graphBaseUrl: 'https://graph.microsoft.com',
    authorityHost: 'https://login.microsoftonline.com'
  });
  assert.equal(result.success, true);
});
