import { IRaceRepository } from '@core/racing/domain/repositories/IRaceRepository';
import { Race, type RaceStatusValue } from '@core/racing/domain/entities/Race';
import { Logger } from '@core/shared/application';

export class InMemoryRaceRepository implements IRaceRepository {
  private races: Map<string, Race> = new Map();

  constructor(private readonly logger: Logger) {
    this.logger.info('InMemoryRaceRepository initialized.');
  }

  async findById(id: string): Promise<Race | null> {
    this.logger.debug(`[InMemoryRaceRepository] Finding race by ID: ${id}`);
    const race = this.races.get(id) ?? null;
    if (race) {
      this.logger.info(`Found race by ID: ${id}.`);
    } else {
      this.logger.warn(`Race with ID ${id} not found.`);
    }
    return Promise.resolve(race);
  }

  async findAll(): Promise<Race[]> {
    this.logger.debug('[InMemoryRaceRepository] Finding all races.');
    return Promise.resolve(Array.from(this.races.values()));
  }

  async findByLeagueId(leagueId: string): Promise<Race[]> {
    this.logger.debug(`[InMemoryRaceRepository] Finding races by league ID: ${leagueId}`);
    const races = Array.from(this.races.values()).filter(race => race.leagueId === leagueId);
    this.logger.info(`Found ${races.length} races for league ID: ${leagueId}.`);
    return Promise.resolve(races);
  }

  async findUpcomingByLeagueId(leagueId: string): Promise<Race[]> {
    this.logger.debug(`[InMemoryRaceRepository] Finding upcoming races by league ID: ${leagueId}`);
    const now = new Date();
    const upcomingRaces = Array.from(this.races.values()).filter(race =>
      race.leagueId === leagueId && race.status.isScheduled() && race.scheduledAt > now
    );
    this.logger.info(`Found ${upcomingRaces.length} upcoming races for league ID: ${leagueId}.`);
    return Promise.resolve(upcomingRaces);
  }

  async findCompletedByLeagueId(leagueId: string): Promise<Race[]> {
    this.logger.debug(`[InMemoryRaceRepository] Finding completed races by league ID: ${leagueId}`);
    const completedRaces = Array.from(this.races.values()).filter(race =>
      race.leagueId === leagueId && race.status.isCompleted()
    );
    this.logger.info(`Found ${completedRaces.length} completed races for league ID: ${leagueId}.`);
    return Promise.resolve(completedRaces);
  }

  async findByStatus(status: RaceStatusValue): Promise<Race[]> {
    this.logger.debug(`[InMemoryRaceRepository] Finding races by status: ${status}.`);
    const races = Array.from(this.races.values()).filter(
      race => race.status.toString() === status,
    );
    this.logger.info(`Found ${races.length} races with status: ${status}.`);
    return Promise.resolve(races);
  }

  async findByDateRange(startDate: Date, endDate: Date): Promise<Race[]> {
    this.logger.debug(`[InMemoryRaceRepository] Finding races by date range: ${startDate.toISOString()} - ${endDate.toISOString()}.`);
    const races = Array.from(this.races.values()).filter(race =>
      race.scheduledAt >= startDate && race.scheduledAt <= endDate
    );
    this.logger.info(`Found ${races.length} races within date range.`);
    return Promise.resolve(races);
  }

  async create(race: Race): Promise<Race> {
    this.logger.debug(`[InMemoryRaceRepository] Creating race: ${race.id} (${race.track}).`);
    if (this.races.has(race.id)) {
      this.logger.warn(`Race with ID ${race.id} already exists.`);
      throw new Error('Race already exists');
    }
    this.races.set(race.id, race);
    this.logger.info(`Race ${race.id} created successfully.`);
    return Promise.resolve(race);
  }

  async update(race: Race): Promise<Race> {
    this.logger.debug(`[InMemoryRaceRepository] Updating race: ${race.id} (${race.track}).`);
    if (!this.races.has(race.id)) {
      this.logger.warn(`Race with ID ${race.id} not found for update.`);
      throw new Error('Race not found');
    }
    this.races.set(race.id, race);
    this.logger.info(`Race ${race.id} updated successfully.`);
    return Promise.resolve(race);
  }

  async delete(id: string): Promise<void> {
    this.logger.debug(`[InMemoryRaceRepository] Deleting race with ID: ${id}.`);
    if (this.races.delete(id)) {
      this.logger.info(`Race ${id} deleted successfully.`);
    } else {
      this.logger.warn(`Race with ID ${id} not found for deletion.`);
    }
    return Promise.resolve();
  }

  async exists(id: string): Promise<boolean> {
    this.logger.debug(`[InMemoryRaceRepository] Checking existence of race with ID: ${id}.`);
    return Promise.resolve(this.races.has(id));
  }
}
