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

import { DriverStatsOrmEntity } from '../entities/DriverStatsOrmEntity';
import {
    assertInteger,
    assertNonEmptyString,
    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', Number(entity.rating));
    assertInteger(entityName, 'safetyRating', Number(entity.safetyRating));
    assertNumber(entityName, 'sportsmanshipRating', Number(entity.sportsmanshipRating));
    assertInteger(entityName, 'totalRaces', Number(entity.totalRaces));
    assertInteger(entityName, 'wins', Number(entity.wins));
    assertInteger(entityName, 'podiums', Number(entity.podiums));
    assertInteger(entityName, 'dnfs', Number(entity.dnfs));
    assertNumber(entityName, 'avgFinish', Number(entity.avgFinish));
    assertInteger(entityName, 'bestFinish', Number(entity.bestFinish));
    assertInteger(entityName, 'worstFinish', Number(entity.worstFinish));
    assertInteger(entityName, 'consistency', Number(entity.consistency));
    assertNonEmptyString(entityName, 'experienceLevel', entity.experienceLevel);

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

    return result;
  }
}