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

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

import { RaceOrmEntity } from '../entities/RaceOrmEntity';
import { TypeOrmPersistenceSchemaError } from '../errors/TypeOrmPersistenceSchemaError';
import { RaceOrmMapper } from './RaceOrmMapper';

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

    const entity = new RaceOrmEntity();
    entity.id = 'race-1';
    entity.leagueId = '00000000-0000-4000-8000-000000000001';
    entity.scheduledAt = new Date('2025-01-01T00:00:00.000Z');
    entity.track = 'Spa';
    entity.trackId = null;
    entity.car = 'Porsche';
    entity.carId = null;
    entity.sessionType = 'main';
    entity.status = 'scheduled';
    entity.strengthOfField = null;
    entity.registeredCount = null;
    entity.maxParticipants = null;

    if (typeof (Race as any).rehydrate !== 'function') {
      throw new Error('rehydrate-missing');
    }

    const rehydrateSpy = vi.spyOn(Race as any, 'rehydrate');
    const createSpy = vi.spyOn(Race, 'create').mockImplementation(() => {
      throw new Error('create-called');
    });

    const domain = mapper.toDomain(entity);

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

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

    const entity = new RaceOrmEntity();
    entity.id = 'race-1';
    entity.leagueId = '00000000-0000-4000-8000-000000000001';
    entity.scheduledAt = new Date('2025-01-01T00:00:00.000Z');
    entity.track = 'Spa';
    entity.trackId = null;
    entity.car = 'Porsche';
    entity.carId = null;
    entity.sessionType = 123 as unknown as string;
    entity.status = 'scheduled';
    entity.strengthOfField = null;
    entity.registeredCount = null;
    entity.maxParticipants = null;

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