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

import { ResultOrmMapper } from './ResultOrmMapper';
import { ResultOrmEntity } from '../entities/ResultOrmEntity';
import { InvalidResultSchemaError } from '../errors/InvalidResultSchemaError';

describe('ResultOrmMapper', () => {
  it('maps persisted schema guard failures into InvalidResultSchemaError', () => {
    const mapper = new ResultOrmMapper();

    const entity = new ResultOrmEntity();
    entity.id = '';
    entity.raceId = 'race-1';
    entity.driverId = 'driver-1';
    entity.position = 1;
    entity.fastestLap = 0;
    entity.incidents = 0;
    entity.startPosition = 1;

    expect(() => mapper.toDomain(entity)).toThrow(InvalidResultSchemaError);

    try {
      mapper.toDomain(entity);
    } catch (error) {
      expect(error).toBeInstanceOf(InvalidResultSchemaError);
      const schemaError = error as InvalidResultSchemaError;
      expect(schemaError.entityName).toBe('Result');
      expect(schemaError.fieldName).toBe('id');
      expect(schemaError.reason).toBe('empty_string');
    }
  });

  it('wraps domain rehydrate failures into InvalidResultSchemaError (no mapper-level business validation)', () => {
    const mapper = new ResultOrmMapper();

    const entity = new ResultOrmEntity();
    entity.id = 'result-1';
    entity.raceId = 'race-1';
    entity.driverId = 'driver-1';
    entity.position = 0; // schema ok (integer), domain invalid (Position)
    entity.fastestLap = 0;
    entity.incidents = 0;
    entity.startPosition = 1;

    try {
      mapper.toDomain(entity);
      throw new Error('Expected mapper.toDomain to throw');
    } catch (error) {
      expect(error).toBeInstanceOf(InvalidResultSchemaError);
      const schemaError = error as InvalidResultSchemaError;
      expect(schemaError.entityName).toBe('Result');
      expect(schemaError.reason).toBe('invalid_shape');
    }
  });
});