/**
 * In-memory implementation of IRaceEventRepository for development/testing.
 */
import type { RaceEvent } from '@core/racing/domain/entities/RaceEvent';
import type { RaceEventRepository } from '@core/racing/domain/repositories/RaceEventRepository';
import type { Logger } from '@core/shared/domain/Logger';

export class InMemoryRaceEventRepository implements RaceEventRepository {
  private raceEvents: Map<string, RaceEvent> = new Map();
  private readonly logger: Logger;

  constructor(logger: Logger) {
    this.logger = logger;
    this.logger.info('InMemoryRaceEventRepository initialized.');
  }

  async findById(id: string): Promise<RaceEvent | null> {
    this.logger.debug(`Finding race event by id: ${id}`);
    try {
      const event = this.raceEvents.get(id) ?? null;
      if (event) {
        this.logger.info(`Found race event: ${event.id}`);
      } else {
        this.logger.warn(`Race event with id ${id} not found.`);
      }
      return event;
    } catch (error) {
      this.logger.error(`Error finding race event by id ${id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findAll(): Promise<RaceEvent[]> {
    this.logger.debug('Finding all race events.');
    try {
      const events = Array.from(this.raceEvents.values());
      this.logger.info(`Found ${events.length} race events.`);
      return events;
    } catch (error) {
      this.logger.error('Error finding all race events:', error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findBySeasonId(seasonId: string): Promise<RaceEvent[]> {
    this.logger.debug(`Finding race events by season id: ${seasonId}`);
    try {
      const events = Array.from(this.raceEvents.values()).filter(
        raceEvent => raceEvent.seasonId === seasonId
      );
      this.logger.info(`Found ${events.length} race events for season id: ${seasonId}.`);
      return events;
    } catch (error) {
      this.logger.error(`Error finding race events by season id ${seasonId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findByLeagueId(leagueId: string): Promise<RaceEvent[]> {
    this.logger.debug(`Finding race events by league id: ${leagueId}`);
    try {
      const events = Array.from(this.raceEvents.values()).filter(
        raceEvent => raceEvent.leagueId === leagueId
      );
      this.logger.info(`Found ${events.length} race events for league id: ${leagueId}.`);
      return events;
    } catch (error) {
      this.logger.error(`Error finding race events by league id ${leagueId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findByStatus(status: string): Promise<RaceEvent[]> {
    this.logger.debug(`Finding race events by status: ${status}`);
    try {
      const events = Array.from(this.raceEvents.values()).filter(
        raceEvent => raceEvent.status === status
      );
      this.logger.info(`Found ${events.length} race events with status: ${status}.`);
      return events;
    } catch (error) {
      this.logger.error(`Error finding race events by status ${status}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findAwaitingStewardingClose(): Promise<RaceEvent[]> {
    this.logger.debug('Finding race events awaiting stewarding close.');
    try {
      const now = new Date();
      const events = Array.from(this.raceEvents.values()).filter(
        raceEvent =>
          raceEvent.status === 'awaiting_stewarding' &&
          raceEvent.stewardingClosesAt &&
          raceEvent.stewardingClosesAt <= now
      );
      this.logger.info(`Found ${events.length} race events awaiting stewarding close.`);
      return events;
    } catch (error) {
      this.logger.error('Error finding race events awaiting stewarding close:', error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async create(raceEvent: RaceEvent): Promise<RaceEvent> {
    this.logger.debug(`Creating race event: ${raceEvent.id}`);
    try {
      this.raceEvents.set(raceEvent.id, raceEvent);
      this.logger.info(`Race event ${raceEvent.id} created successfully.`);
      return raceEvent;
    } catch (error) {
      this.logger.error(`Error creating race event ${raceEvent.id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async update(raceEvent: RaceEvent): Promise<RaceEvent> {
    this.logger.debug(`Updating race event: ${raceEvent.id}`);
    try {
      if (!this.raceEvents.has(raceEvent.id)) {
        this.logger.warn(`Race event with id ${raceEvent.id} not found for update. Creating new.`);
      }
      this.raceEvents.set(raceEvent.id, raceEvent);
      this.logger.info(`Race event ${raceEvent.id} updated successfully.`);
      return raceEvent;
    } catch (error) {
      this.logger.error(`Error updating race event ${raceEvent.id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async delete(id: string): Promise<void> {
    this.logger.debug(`Deleting race event: ${id}`);
    try {
      if (this.raceEvents.delete(id)) {
        this.logger.info(`Race event ${id} deleted successfully.`);
      } else {
        this.logger.warn(`Race event with id ${id} not found for deletion.`);
      }
    } catch (error) {
      this.logger.error(`Error deleting race event ${id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async exists(id: string): Promise<boolean> {
    this.logger.debug(`Checking existence of race event with id: ${id}`);
    try {
      const exists = this.raceEvents.has(id);
      this.logger.debug(`Race event ${id} exists: ${exists}.`);
      return exists;
    } catch (error) {
      this.logger.error(`Error checking existence of race event with id ${id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  // Test helper methods
  clear(): void {
    this.logger.debug('Clearing all race events.');
    this.raceEvents.clear();
    this.logger.info('All race events cleared.');
  }

  getAll(): RaceEvent[] {
    this.logger.debug('Getting all race events.');
    try {
      const events = Array.from(this.raceEvents.values());
      this.logger.info(`Retrieved ${events.length} race events.`);
      return events;
    } catch (error) {
      this.logger.error(`Error getting all race events:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }
}