import { TeamRatingSnapshot } from '@core/racing/domain/services/TeamRatingSnapshotCalculator';
import { TeamRatingValue } from '@core/racing/domain/value-objects/TeamRatingValue';
import { TeamRatingOrmEntity } from '../entities/TeamRatingOrmEntity';

/**
 * Mapper: TeamRatingOrmMapper
 * 
 * Converts between TeamRatingSnapshot domain value and TeamRatingOrmEntity.
 */
export class TeamRatingOrmMapper {
  /**
   * Convert ORM entity to domain snapshot
   */
  static toDomain(entity: TeamRatingOrmEntity): TeamRatingSnapshot {
    return {
      teamId: entity.teamId,
      driving: TeamRatingValue.create(entity.driving.value),
      adminTrust: TeamRatingValue.create(entity.adminTrust.value),
      overall: entity.overall,
      lastUpdated: entity.updatedAt,
      eventCount: entity.driving.sampleSize + entity.adminTrust.sampleSize,
    };
  }

  /**
   * Convert domain snapshot to ORM entity
   */
  static toOrmEntity(snapshot: TeamRatingSnapshot): TeamRatingOrmEntity {
    const entity = new TeamRatingOrmEntity();
    entity.teamId = snapshot.teamId;
    
    // Calculate confidence based on event count
    const confidence = 1 - Math.exp(-snapshot.eventCount / 20);
    
    entity.driving = {
      value: snapshot.driving.value,
      confidence: confidence,
      sampleSize: snapshot.eventCount,
      trend: snapshot.driving.value > 50 ? 'rising' : snapshot.driving.value < 50 ? 'falling' : 'stable',
      lastUpdated: snapshot.lastUpdated,
    };
    
    entity.adminTrust = {
      value: snapshot.adminTrust.value,
      confidence: confidence,
      sampleSize: snapshot.eventCount,
      trend: snapshot.adminTrust.value > 50 ? 'rising' : snapshot.adminTrust.value < 50 ? 'falling' : 'stable',
      lastUpdated: snapshot.lastUpdated,
    };
    
    entity.overall = snapshot.overall;
    entity.calculatorVersion = '1.0';
    entity.createdAt = snapshot.lastUpdated;
    entity.updatedAt = snapshot.lastUpdated;
    
    return entity;
  }
}