import { ExternalGameRatingProfile } from '@core/identity/domain/entities/ExternalGameRatingProfile';
import { ExternalGameRatingProfileOrmEntity } from '../entities/ExternalGameRatingProfileOrmEntity';

/**
 * Mapper: ExternalGameRatingProfileOrmMapper
 * 
 * Converts between ExternalGameRatingProfile domain entity and 
 * ExternalGameRatingProfileOrmEntity.
 */
export class ExternalGameRatingProfileOrmMapper {
  /**
   * Convert ORM entity to domain entity
   */
  static toDomain(entity: ExternalGameRatingProfileOrmEntity): ExternalGameRatingProfile {
    return ExternalGameRatingProfile.restore({
      userId: entity.userId,
      gameKey: entity.gameKey,
      ratings: entity.ratings.map(r => ({
        type: r.type,
        gameKey: r.gameKey,
        value: r.value,
      })),
      provenance: {
        source: entity.provenance.source,
        lastSyncedAt: entity.provenance.lastSyncedAt,
        verified: entity.provenance.verified,
      },
    });
  }

  /**
   * Convert domain entity to ORM entity
   */
  static toOrmEntity(domain: ExternalGameRatingProfile): ExternalGameRatingProfileOrmEntity {
    const entity = new ExternalGameRatingProfileOrmEntity();
    
    entity.userId = domain.userId.toString();
    entity.gameKey = domain.gameKey.toString();
    
    // Convert ratings map to array
    entity.ratings = Array.from(domain.ratings.entries()).map(([type, rating]) => ({
      type,
      gameKey: rating.gameKey.toString(),
      value: rating.value,
    }));
    
    // Convert provenance
    entity.provenance = {
      source: domain.provenance.source,
      lastSyncedAt: domain.provenance.lastSyncedAt,
      verified: domain.provenance.verified,
    };
    
    // Set timestamps (use current time for new entities)
    const now = new Date();
    entity.createdAt = now;
    entity.updatedAt = now;
    
    return entity;
  }

  /**
   * Update existing ORM entity from domain entity
   */
  static updateOrmEntity(
    entity: ExternalGameRatingProfileOrmEntity,
    domain: ExternalGameRatingProfile
  ): ExternalGameRatingProfileOrmEntity {
    entity.ratings = Array.from(domain.ratings.entries()).map(([type, rating]) => ({
      type,
      gameKey: rating.gameKey.toString(),
      value: rating.value,
    }));
    
    entity.provenance = {
      source: domain.provenance.source,
      lastSyncedAt: domain.provenance.lastSyncedAt,
      verified: domain.provenance.verified,
    };
    
    entity.updatedAt = new Date();
    
    return entity;
  }
}