import { User } from '../../shared-kernel';
import { shouldApplyAvatarTransfer, shouldRequestAvatarData } from './user-avatar.effects';

function createUser(overrides: Partial<User> = {}): User {
  return {
    id: 'user-1',
    oderId: 'oder-1',
    username: 'alice',
    displayName: 'Alice',
    status: 'online',
    role: 'member',
    joinedAt: Date.now(),
    ...overrides
  };
}

describe('user avatar sync helpers', () => {
  it('requests avatar data when the remote version is newer', () => {
    const existingUser = createUser({
      avatarUrl: 'data:image/webp;base64,older',
      avatarHash: 'hash-1',
      avatarUpdatedAt: 100
    });

    expect(shouldRequestAvatarData(existingUser, {
      avatarHash: 'hash-2',
      avatarUpdatedAt: 200
    })).toBe(true);
  });

  it('requests avatar data when metadata matches but the local payload is missing', () => {
    const existingUser = createUser({
      avatarHash: 'hash-1',
      avatarMime: 'image/gif',
      avatarUpdatedAt: 200
    });

    expect(shouldRequestAvatarData(existingUser, {
      avatarHash: 'hash-1',
      avatarUpdatedAt: 200
    })).toBe(true);
  });

  it('does not request avatar data when the same payload is already present', () => {
    const existingUser = createUser({
      avatarUrl: 'data:image/gif;base64,current',
      avatarHash: 'hash-1',
      avatarMime: 'image/gif',
      avatarUpdatedAt: 200
    });

    expect(shouldRequestAvatarData(existingUser, {
      avatarHash: 'hash-1',
      avatarUpdatedAt: 200
    })).toBe(false);
  });

  it('applies equal-version transfers when the local payload is missing', () => {
    const existingUser = createUser({
      avatarHash: 'hash-1',
      avatarUpdatedAt: 200
    });

    expect(shouldApplyAvatarTransfer(existingUser, {
      hash: 'hash-1',
      updatedAt: 200
    })).toBe(true);
  });

  it('rejects older avatar transfers', () => {
    const existingUser = createUser({
      avatarUrl: 'data:image/gif;base64,current',
      avatarHash: 'hash-2',
      avatarUpdatedAt: 200
    });

    expect(shouldApplyAvatarTransfer(existingUser, {
      hash: 'hash-1',
      updatedAt: 100
    })).toBe(false);
  });
});
