import { describe, it, expect } from 'vitest';
import { deriveCorsOrigin } from './gateway-config.js';

describe('deriveCorsOrigin', () => {
  describe('localhost / loopback — always http', () => {
    it('localhost port 3000 → http://localhost:3000', () => {
      expect(deriveCorsOrigin('localhost', 3000)).toBe('http://localhost:3000');
    });

    it('127.0.0.1 port 3000 → http://127.0.0.1:3000', () => {
      expect(deriveCorsOrigin('127.0.0.1', 3000)).toBe('http://127.0.0.1:3000');
    });

    it('localhost port 80 omits port suffix', () => {
      expect(deriveCorsOrigin('localhost', 80)).toBe('http://localhost');
    });

    it('localhost port 443 still uses http (loopback overrides), includes port', () => {
      // 443 is the https default port, but since localhost forces http, the port
      // is NOT the default for http (80), so it must be included.
      expect(deriveCorsOrigin('localhost', 443)).toBe('http://localhost:443');
    });

    it('useHttps=false on localhost keeps http', () => {
      expect(deriveCorsOrigin('localhost', 3000, false)).toBe('http://localhost:3000');
    });

    it('useHttps=true on localhost still uses http (loopback wins)', () => {
      // Passing useHttps=true for localhost is unusual but the function honours
      // the explicit override — loopback detection only applies when useHttps is
      // undefined (auto-detect path).
      expect(deriveCorsOrigin('localhost', 3000, true)).toBe('https://localhost:3000');
    });
  });

  describe('remote hostname — defaults to https', () => {
    it('example.com port 3000 → https://example.com:3000', () => {
      expect(deriveCorsOrigin('example.com', 3000)).toBe('https://example.com:3000');
    });

    it('example.com port 443 omits port suffix', () => {
      expect(deriveCorsOrigin('example.com', 443)).toBe('https://example.com');
    });

    it('example.com port 80 → https://example.com:80 (non-default port for https)', () => {
      expect(deriveCorsOrigin('example.com', 80)).toBe('https://example.com:80');
    });

    it('useHttps=false on remote host uses http', () => {
      expect(deriveCorsOrigin('example.com', 3000, false)).toBe('http://example.com:3000');
    });

    it('useHttps=false on remote host, port 80 omits suffix', () => {
      expect(deriveCorsOrigin('example.com', 80, false)).toBe('http://example.com');
    });
  });

  describe('subdomain and non-standard hostnames', () => {
    it('sub.domain.example.com defaults to https', () => {
      expect(deriveCorsOrigin('sub.domain.example.com', 3000)).toBe(
        'https://sub.domain.example.com:3000',
      );
    });

    it('myserver.local defaults to https (not loopback)', () => {
      expect(deriveCorsOrigin('myserver.local', 8080)).toBe('https://myserver.local:8080');
    });
  });
});
