// Unit tests for validateUrl.normalizeHttpUrl / isSafeHttpUrl.
// Used by P1-UX-3 to gate lesson_plans.meet_url and .classroom_url.

const { isSafeHttpUrl, normalizeHttpUrl } = require('../src/utils/validateUrl');

describe('isSafeHttpUrl', () => {
  it('treats null/undefined/empty as valid (means "no link")', () => {
    expect(isSafeHttpUrl(null)).toBe(true);
    expect(isSafeHttpUrl(undefined)).toBe(true);
    expect(isSafeHttpUrl('')).toBe(true);
  });

  it('rejects non-string values', () => {
    expect(isSafeHttpUrl(42)).toBe(false);
    expect(isSafeHttpUrl({})).toBe(false);
    expect(isSafeHttpUrl([])).toBe(false);
    expect(isSafeHttpUrl(true)).toBe(false);
  });

  it('accepts http and https URLs', () => {
    expect(isSafeHttpUrl('http://meet.example.com/abc')).toBe(true);
    expect(isSafeHttpUrl('https://meet.google.com/abc-defg-hij')).toBe(true);
    expect(isSafeHttpUrl('https://classroom.google.com/c/12345')).toBe(true);
  });

  it('rejects non-http schemes', () => {
    expect(isSafeHttpUrl('javascript:alert(1)')).toBe(false);
    expect(isSafeHttpUrl('ftp://files.example.com')).toBe(false);
    expect(isSafeHttpUrl('file:///etc/passwd')).toBe(false);
    expect(isSafeHttpUrl('data:text/plain;base64,QQ==')).toBe(false);
  });

  it('rejects unparseable strings', () => {
    expect(isSafeHttpUrl('not a url')).toBe(false);
    expect(isSafeHttpUrl('://no-scheme')).toBe(false);
    expect(isSafeHttpUrl('http://')).toBe(false);
  });
});

describe('normalizeHttpUrl', () => {
  it('returns null for null/undefined', () => {
    expect(normalizeHttpUrl(null)).toBe(null);
    expect(normalizeHttpUrl(undefined)).toBe(null);
  });

  it('returns null for empty / whitespace-only strings', () => {
    expect(normalizeHttpUrl('')).toBe(null);
    expect(normalizeHttpUrl('   ')).toBe(null);
  });

  it('trims a valid URL and returns it', () => {
    expect(normalizeHttpUrl('  https://meet.google.com/abc  ')).toBe(
      'https://meet.google.com/abc'
    );
  });

  it('returns null (NOT the original input) for invalid URLs', () => {
    expect(normalizeHttpUrl('javascript:alert(1)')).toBe(null);
    expect(normalizeHttpUrl('not a url')).toBe(null);
  });

  it('returns null for non-string values', () => {
    expect(normalizeHttpUrl(123)).toBe(null);
    expect(normalizeHttpUrl({})).toBe(null);
  });
});
