import type { DataSource } from 'typeorm';

import type { ISeasonRepository } from '@core/racing/domain/repositories/ISeasonRepository';
import { Season } from '@core/racing/domain/entities/season/Season';

import { SeasonOrmEntity } from '../entities/SeasonOrmEntity';
import { SeasonOrmMapper } from '../mappers/SeasonOrmMapper';

export class TypeOrmSeasonRepository implements ISeasonRepository {
  constructor(
    private readonly dataSource: DataSource,
    private readonly mapper: SeasonOrmMapper,
  ) {}

  async findById(id: string): Promise<Season | null> {
    const repo = this.dataSource.getRepository(SeasonOrmEntity);
    const entity = await repo.findOne({ where: { id } });
    return entity ? this.mapper.toDomain(entity) : null;
  }

  async findByLeagueId(leagueId: string): Promise<Season[]> {
    const repo = this.dataSource.getRepository(SeasonOrmEntity);
    const entities = await repo.find({ where: { leagueId } });
    return entities.map((e) => this.mapper.toDomain(e));
  }

  async create(season: Season): Promise<Season> {
    const repo = this.dataSource.getRepository(SeasonOrmEntity);
    await repo.save(this.mapper.toOrmEntity(season));
    return season;
  }

  async add(season: Season): Promise<void> {
    const repo = this.dataSource.getRepository(SeasonOrmEntity);
    await repo.save(this.mapper.toOrmEntity(season));
  }

  async update(season: Season): Promise<void> {
    const repo = this.dataSource.getRepository(SeasonOrmEntity);
    await repo.save(this.mapper.toOrmEntity(season));
  }

  async listByLeague(leagueId: string): Promise<Season[]> {
    return this.findByLeagueId(leagueId);
  }

  async listActiveByLeague(leagueId: string): Promise<Season[]> {
    const repo = this.dataSource.getRepository(SeasonOrmEntity);
    const entities = await repo.find({ where: { leagueId, status: 'active' } });
    return entities.map((e) => this.mapper.toDomain(e));
  }
}