import type { DataSource } from 'typeorm';

import type { ITeamRatingRepository } from '@core/racing/domain/repositories/ITeamRatingRepository';
import type { TeamRatingSnapshot } from '@core/racing/domain/services/TeamRatingSnapshotCalculator';

import { TeamRatingOrmEntity } from '../entities/TeamRatingOrmEntity';
import { TeamRatingOrmMapper } from '../mappers/TeamRatingOrmMapper';

/**
 * TypeORM Implementation: ITeamRatingRepository
 * 
 * Persists and retrieves TeamRating snapshots for fast reads.
 */
export class TypeOrmTeamRatingRepository implements ITeamRatingRepository {
  constructor(private readonly dataSource: DataSource) {}

  async findByTeamId(teamId: string): Promise<TeamRatingSnapshot | null> {
    const repo = this.dataSource.getRepository(TeamRatingOrmEntity);
    const entity = await repo.findOne({ where: { teamId } });
    
    if (!entity) {
      return null;
    }
    
    return TeamRatingOrmMapper.toDomain(entity);
  }

  async save(teamRating: TeamRatingSnapshot): Promise<TeamRatingSnapshot> {
    const repo = this.dataSource.getRepository(TeamRatingOrmEntity);
    const entity = TeamRatingOrmMapper.toOrmEntity(teamRating);
    await repo.save(entity);
    return teamRating;
  }
}