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

import { TeamStatsOrmEntity } from '../entities/TeamStatsOrmEntity';
import { TeamStatsOrmMapper } from '../mappers/TeamStatsOrmMapper';

export class TypeOrmTeamStatsRepository implements ITeamStatsRepository {
  constructor(
    private readonly repo: Repository<TeamStatsOrmEntity>,
    private readonly mapper: TeamStatsOrmMapper,
  ) {}

  async getTeamStats(teamId: string): Promise<TeamStats | null> {
    const entity = await this.repo.findOne({ where: { teamId } });
    return entity ? this.mapper.toDomain(entity) : null;
  }

  async saveTeamStats(teamId: string, stats: TeamStats): Promise<void> {
    const entity = this.mapper.toOrmEntity(teamId, stats);
    await this.repo.save(entity);
  }

  async getAllStats(): Promise<Map<string, TeamStats>> {
    const entities = await this.repo.find();
    const statsMap = new Map<string, TeamStats>();
    
    for (const entity of entities) {
      statsMap.set(entity.teamId, this.mapper.toDomain(entity));
    }
    
    return statsMap;
  }

  async clear(): Promise<void> {
    await this.repo.clear();
  }
}
