import {
  describe,
  expect,
  it
} from 'vitest';
import {
  isSignalServerTagUrl,
  presentSignalServerTag,
  resolveEndpointSignalServerTag,
  resolveUserHomeSignalServerTag
} from './signal-server-tag.rules';
import type { ServerEndpoint } from '../models/server-directory.model';

describe('signal-server-tag.rules', () => {
  const endpoints: ServerEndpoint[] = [
    {
      id: 'endpoint-1',
      name: 'Primary',
      url: 'http://signal.example.com:3001',
      isActive: true,
      isDefault: true,
      status: 'online',
      serverTag: 'EU'
    },
    {
      id: 'endpoint-2',
      name: 'Fallback',
      url: 'https://signal-backup.example.com',
      isActive: true,
      isDefault: false,
      status: 'online'
    }
  ];

  it('uses configured serverTag when present on an endpoint', () => {
    expect(resolveEndpointSignalServerTag(endpoints[0])).toBe('EU');
  });

  it('falls back to endpoint url when serverTag is missing', () => {
    expect(resolveEndpointSignalServerTag(endpoints[1])).toBe('https://signal-backup.example.com');
  });

  it('resolves a user home signal server tag from known endpoints', () => {
    expect(resolveUserHomeSignalServerTag('http://signal.example.com:3001/', endpoints)).toBe('EU');
  });

  it('falls back to the home signal server url when the endpoint is unknown', () => {
    expect(resolveUserHomeSignalServerTag('http://unknown.example.com:3001', endpoints))
      .toBe('http://unknown.example.com:3001');
  });

  it('returns undefined when the user has no home signal server url', () => {
    expect(resolveUserHomeSignalServerTag(undefined, endpoints)).toBeUndefined();
  });

  it('detects http and https values as urls', () => {
    expect(isSignalServerTagUrl('http://signal.example.com:3001')).toBe(true);
    expect(isSignalServerTagUrl('https://signal.example.com')).toBe(true);
    expect(isSignalServerTagUrl('EU')).toBe(false);
  });

  it('prefixes non-url tags with #', () => {
    expect(presentSignalServerTag('EU')).toEqual({
      kind: 'label',
      label: 'EU',
      display: '#EU'
    });
  });

  it('strips an existing # before re-prefixing label tags', () => {
    expect(presentSignalServerTag('#sweden')).toEqual({
      kind: 'label',
      label: 'sweden',
      display: '#sweden'
    });
  });

  it('presents url tags as globe tooltip targets', () => {
    expect(presentSignalServerTag('https://signal.example.com')).toEqual({
      kind: 'url',
      url: 'https://signal.example.com'
    });
  });
});
