import { describe, expect, it, vi } from 'vitest';

import { Avatar } from '@core/media/domain/entities/Avatar';

import { AvatarOrmEntity } from '../entities/AvatarOrmEntity';
import { TypeOrmMediaSchemaError } from '../errors/TypeOrmMediaSchemaError';
import { AvatarOrmMapper } from './AvatarOrmMapper';

describe('AvatarOrmMapper', () => {
  it('toDomain preserves persisted identity and uses reconstitute semantics', () => {
    const mapper = new AvatarOrmMapper();

    const entity = new AvatarOrmEntity();
    entity.id = '00000000-0000-4000-8000-000000000001';
    entity.driverId = 'driver-123';
    entity.mediaUrl = 'https://cdn.example.com/avatars/avatar-1.png';
    entity.selectedAt = new Date('2025-01-01T00:00:00.000Z');
    entity.isActive = true;

    const reconstituteSpy = vi.spyOn(Avatar as unknown as { reconstitute: (...args: unknown[]) => unknown }, 'reconstitute');

    const domain = mapper.toDomain(entity);

    expect(domain.id).toBe(entity.id);
    expect(domain.driverId).toBe(entity.driverId);
    expect(domain.mediaUrl.value).toBe(entity.mediaUrl);
    expect(domain.isActive).toBe(entity.isActive);

    expect(reconstituteSpy).toHaveBeenCalled();
  });

  it('toDomain validates persisted shape', () => {
    const mapper = new AvatarOrmMapper();

    const entity = new AvatarOrmEntity();
    entity.id = '00000000-0000-4000-8000-000000000001';
    entity.driverId = 123 as unknown as string;
    entity.mediaUrl = 'https://cdn.example.com/avatars/avatar-1.png';
    entity.selectedAt = new Date('2025-01-01T00:00:00.000Z');
    entity.isActive = true;

    try {
      mapper.toDomain(entity);
      throw new Error('expected-to-throw');
    } catch (error) {
      expect(error).toBeInstanceOf(TypeOrmMediaSchemaError);
      expect(error).toMatchObject({
        entityName: 'Avatar',
        fieldName: 'driverId',
        reason: 'not_string',
      });
    }
  });

  it('toOrmEntity converts domain entity to ORM entity', () => {
    const mapper = new AvatarOrmMapper();

    const domain = Avatar.create({
      id: '00000000-0000-4000-8000-000000000001',
      driverId: 'driver-123',
      mediaUrl: 'https://cdn.example.com/avatars/avatar-1.png',
    });

    const entity = mapper.toOrmEntity(domain);

    expect(entity.id).toBe(domain.id);
    expect(entity.driverId).toBe(domain.driverId);
    expect(entity.mediaUrl).toBe(domain.mediaUrl.value);
    expect(entity.isActive).toBe(true);
  });
});
