import type { DataSource } from 'typeorm';

import { LeagueScoringConfig } from '@core/racing/domain/entities/LeagueScoringConfig';
import type { LeagueScoringConfigRepository } from '@core/racing/domain/repositories/LeagueScoringConfigRepository';

import { LeagueScoringConfigOrmEntity } from '../entities/LeagueScoringConfigOrmEntity';
import { LeagueScoringConfigOrmMapper } from '../mappers/LeagueScoringConfigOrmMapper';

export class TypeOrmLeagueScoringConfigRepository implements LeagueScoringConfigRepository {
  constructor(
    private readonly dataSource: DataSource,
    private readonly mapper: LeagueScoringConfigOrmMapper,
  ) {}

  async findBySeasonId(seasonId: string): Promise<LeagueScoringConfig | null> {
    const repo = this.dataSource.getRepository(LeagueScoringConfigOrmEntity);
    const entity = await repo.findOne({ where: { seasonId } });
    return entity ? this.mapper.toDomain(entity) : null;
  }

  async save(config: LeagueScoringConfig): Promise<LeagueScoringConfig> {
    const repo = this.dataSource.getRepository(LeagueScoringConfigOrmEntity);
    await repo.save(this.mapper.toOrmEntity(config));
    return config;
  }
}