import { describe, expect, it } from 'vitest';
import { dataUrlToBytes, isRemoteAvatarUrl } from './avatarCache';

describe('isRemoteAvatarUrl', () => {
  it('matches http and https URLs only', () => {
    expect(isRemoteAvatarUrl('http://192.168.1.5:8666/api/avatars/alice.png?v=1')).toBe(true);
    expect(isRemoteAvatarUrl('https://rc.example.com/api/avatars/alice.png')).toBe(true);
    expect(isRemoteAvatarUrl('HTTP://HOST/a.png')).toBe(true);
  });

  it('passes through data/blob/bundled-asset sources and empties', () => {
    expect(isRemoteAvatarUrl('data:image/png;base64,AAAA')).toBe(false);
    expect(isRemoteAvatarUrl('blob:tauri://localhost/xyz')).toBe(false);
    expect(isRemoteAvatarUrl('assets/account.svg')).toBe(false);
    expect(isRemoteAvatarUrl('')).toBe(false);
    expect(isRemoteAvatarUrl(null)).toBe(false);
    expect(isRemoteAvatarUrl(undefined)).toBe(false);
  });
});

describe('dataUrlToBytes', () => {
  it('decodes a base64 data URL to its raw bytes', () => {
    // PNG magic: 89 50 4E 47 0D 0A 1A 0A → base64 "iVBORw0KGgo="
    const bytes = dataUrlToBytes('data:image/png;base64,iVBORw0KGgo=');
    expect(Array.from(bytes.slice(0, 8))).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  });

  it('round-trips arbitrary binary through base64', () => {
    const original = Uint8Array.from({ length: 256 }, (_, i) => i);
    const b64 = btoa(String.fromCharCode(...original));
    const bytes = dataUrlToBytes(`data:application/octet-stream;base64,${b64}`);
    expect(Array.from(bytes)).toEqual(Array.from(original));
  });

  it('decodes percent-encoded (non-base64) data URLs as UTF-8', () => {
    const bytes = dataUrlToBytes('data:text/plain,hello%20world');
    expect(new TextDecoder().decode(bytes)).toBe('hello world');
  });

  it('rejects strings that are not data URLs', () => {
    expect(() => dataUrlToBytes('http://host/a.png')).toThrow();
    expect(() => dataUrlToBytes('data:image/png;base64')).toThrow(); // no comma
    expect(() => dataUrlToBytes(undefined)).toThrow();
  });
});
