import type { DriverStats } from '@core/racing/application/use-cases/IDriverStatsUseCase';

import { DriverStatsOrmEntity } from '../entities/DriverStatsOrmEntity';
import {
  assertNonEmptyString,
  assertInteger,
  assertNumber
} from '../schema/TypeOrmSchemaGuards';

export class DriverStatsOrmMapper {
  toOrmEntity(driverId: string, domain: DriverStats): DriverStatsOrmEntity {
    const entity = new DriverStatsOrmEntity();
    entity.driverId = driverId;
    entity.rating = domain.rating;
    entity.safetyRating = domain.safetyRating;
    entity.sportsmanshipRating = domain.sportsmanshipRating;
    entity.totalRaces = domain.totalRaces;
    entity.wins = domain.wins;
    entity.podiums = domain.podiums;
    entity.dnfs = domain.dnfs;
    entity.avgFinish = domain.avgFinish;
    entity.bestFinish = domain.bestFinish;
    entity.worstFinish = domain.worstFinish;
    entity.consistency = domain.consistency;
    entity.experienceLevel = domain.experienceLevel;
    entity.overallRank = domain.overallRank ?? null;
    return entity;
  }

  toDomain(entity: DriverStatsOrmEntity): DriverStats {
    const entityName = 'DriverStats';

    assertNonEmptyString(entityName, 'driverId', entity.driverId);
    assertInteger(entityName, 'rating', entity.rating);
    assertInteger(entityName, 'safetyRating', entity.safetyRating);
    assertInteger(entityName, 'sportsmanshipRating', entity.sportsmanshipRating);
    assertInteger(entityName, 'totalRaces', entity.totalRaces);
    assertInteger(entityName, 'wins', entity.wins);
    assertInteger(entityName, 'podiums', entity.podiums);
    assertInteger(entityName, 'dnfs', entity.dnfs);
    assertNumber(entityName, 'avgFinish', entity.avgFinish);
    assertInteger(entityName, 'bestFinish', entity.bestFinish);
    assertInteger(entityName, 'worstFinish', entity.worstFinish);
    assertInteger(entityName, 'consistency', entity.consistency);
    assertNonEmptyString(entityName, 'experienceLevel', entity.experienceLevel);

    const result: DriverStats = {
      rating: entity.rating,
      safetyRating: entity.safetyRating,
      sportsmanshipRating: entity.sportsmanshipRating,
      totalRaces: entity.totalRaces,
      wins: entity.wins,
      podiums: entity.podiums,
      dnfs: entity.dnfs,
      avgFinish: entity.avgFinish,
      bestFinish: entity.bestFinish,
      worstFinish: entity.worstFinish,
      consistency: entity.consistency,
      experienceLevel: entity.experienceLevel,
      overallRank: entity.overallRank ?? null,
    };

    return result;
  }
}