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

import { StandingOrmMapper } from './StandingOrmMapper';
import { StandingOrmEntity } from '../entities/StandingOrmEntity';
import { InvalidStandingSchemaError } from '../errors/InvalidStandingSchemaError';

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

    const entity = new StandingOrmEntity();
    entity.id = 'league-1:driver-1';
    entity.leagueId = '';
    entity.driverId = 'driver-1';
    entity.points = 0;
    entity.wins = 0;
    entity.position = 1;
    entity.racesCompleted = 0;

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

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

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

    const entity = new StandingOrmEntity();
    entity.id = 'league-1:driver-1';
    entity.leagueId = 'league-1';
    entity.driverId = 'driver-1';
    entity.points = 0;
    entity.wins = 0;
    entity.position = 0; // schema ok (integer), domain invalid (Position)
    entity.racesCompleted = 0;

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