import type { TeamStats } from '@core/racing/domain/repositories/ITeamStatsRepository';

import { TeamStatsOrmEntity } from '../entities/TeamStatsOrmEntity';
import { 
  assertNonEmptyString, 
  assertInteger,
  assertArray,
  assertEnumValue
} from '../schema/TypeOrmSchemaGuards';

const PERFORMANCE_LEVELS = ['beginner', 'intermediate', 'advanced', 'pro'] as const;
const SPECIALIZATIONS = ['endurance', 'sprint', 'mixed'] as const;

export class TeamStatsOrmMapper {
  toOrmEntity(teamId: string, domain: TeamStats): TeamStatsOrmEntity {
    const entity = new TeamStatsOrmEntity();
    entity.teamId = teamId;
    entity.performanceLevel = domain.performanceLevel;
    entity.specialization = domain.specialization;
    entity.region = domain.region;
    entity.languages = domain.languages;
    entity.totalWins = domain.totalWins;
    entity.totalRaces = domain.totalRaces;
    entity.rating = domain.rating;
    entity.category = domain.category ?? null;
    return entity;
  }

  toDomain(entity: TeamStatsOrmEntity): TeamStats {
    const entityName = 'TeamStats';

    assertNonEmptyString(entityName, 'teamId', entity.teamId);
    assertEnumValue(entityName, 'performanceLevel', entity.performanceLevel, PERFORMANCE_LEVELS);
    assertEnumValue(entityName, 'specialization', entity.specialization, SPECIALIZATIONS);
    assertNonEmptyString(entityName, 'region', entity.region);
    assertArray(entityName, 'languages', entity.languages);
    assertInteger(entityName, 'totalWins', entity.totalWins);
    assertInteger(entityName, 'totalRaces', entity.totalRaces);
    assertInteger(entityName, 'rating', entity.rating);

    const result: TeamStats = {
      performanceLevel: entity.performanceLevel as 'beginner' | 'intermediate' | 'advanced' | 'pro',
      specialization: entity.specialization as 'endurance' | 'sprint' | 'mixed',
      region: entity.region,
      languages: entity.languages,
      totalWins: entity.totalWins,
      totalRaces: entity.totalRaces,
      rating: entity.rating,
    };

    if (entity.category !== null && entity.category !== undefined) {
      result.category = entity.category;
    }

    return result;
  }
}
