import type { IDriverStatsRepository } from '@core/racing/domain/repositories/IDriverStatsRepository';
import type { DriverStats } from '@core/racing/application/use-cases/IDriverStatsUseCase';
import type { Repository } from 'typeorm';

import { DriverStatsOrmEntity } from '../entities/DriverStatsOrmEntity';
import { DriverStatsOrmMapper } from '../mappers/DriverStatsOrmMapper';

export class TypeOrmDriverStatsRepository implements IDriverStatsRepository {
  constructor(
    private readonly repo: Repository<DriverStatsOrmEntity>,
    private readonly mapper: DriverStatsOrmMapper,
  ) {}

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

  getDriverStatsSync(_driverId: string): DriverStats | null {
    // TypeORM repositories don't support synchronous operations
    // This method is provided for interface compatibility but should not be used
    // with TypeORM implementations. Return null to indicate it's not supported.
    return null;
  }

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

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

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