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

import { Driver } from '@core/racing/domain/entities/Driver';

import { DriverOrmEntity } from '../entities/DriverOrmEntity';
import { TypeOrmPersistenceSchemaError } from '../errors/TypeOrmPersistenceSchemaError';
import { DriverOrmMapper } from './DriverOrmMapper';

describe('DriverOrmMapper', () => {
  it('toDomain preserves persisted identity and uses rehydrate semantics (does not call create)', () => {
    const mapper = new DriverOrmMapper();

    const entity = new DriverOrmEntity();
    entity.id = '00000000-0000-4000-8000-000000000001';
    entity.iracingId = '12345';
    entity.name = 'Max Verstappen';
    entity.country = 'DE';
    entity.bio = 'Bio';
    entity.joinedAt = new Date('2025-01-01T00:00:00.000Z');

    if (typeof (Driver as unknown as { rehydrate?: unknown }).rehydrate !== 'function') {
      throw new Error('rehydrate-missing');
    }

    const rehydrateSpy = vi.spyOn(Driver as unknown as { rehydrate: (...args: unknown[]) => unknown }, 'rehydrate');
    const createSpy = vi.spyOn(Driver, 'create').mockImplementation(() => {
      throw new Error('create-called');
    });

    const domain = mapper.toDomain(entity);

    expect(domain.id).toBe(entity.id);
    expect(domain.iracingId.toString()).toBe(entity.iracingId);
    expect(createSpy).not.toHaveBeenCalled();
    expect(rehydrateSpy).toHaveBeenCalled();
  });

  it('toDomain validates persisted shape and throws adapter-scoped base schema error type', () => {
    const mapper = new DriverOrmMapper();

    const entity = new DriverOrmEntity();
    entity.id = '00000000-0000-4000-8000-000000000001';
    entity.iracingId = 123 as unknown as string;
    entity.name = 'Name';
    entity.country = 'DE';
    entity.bio = null;
    entity.joinedAt = new Date('2025-01-01T00:00:00.000Z');

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