/**
 * In-Memory Implementation: ILiveryRepository
 * 
 * Mock repository for testing and development
 */

import type { DriverLivery } from '../../../../core/racing/domain/entities/DriverLivery';
import type { LiveryTemplate } from '../../../../core/racing/domain/entities/LiveryTemplate';
import type { ILiveryRepository } from '../../../../core/racing/domain/repositories/ILiveryRepository';
import type { Logger } from '@core/shared/application';

export class InMemoryLiveryRepository implements ILiveryRepository {
  private driverLiveries: Map<string, DriverLivery> = new Map();
  private templates: Map<string, LiveryTemplate> = new Map();
  private readonly logger: Logger;

  constructor(logger: Logger, seedDriverLiveries?: DriverLivery[], seedTemplates?: LiveryTemplate[]) {
    this.logger = logger;
    this.logger.info('InMemoryLiveryRepository initialized.');
    if (seedDriverLiveries) {
      seedDriverLiveries.forEach(livery => this.driverLiveries.set(livery.id, livery));
      this.logger.debug(`Seeded ${seedDriverLiveries.length} driver liveries.`);
    }
    if (seedTemplates) {
      seedTemplates.forEach(template => this.templates.set(template.id.toString(), template));
      this.logger.debug(`Seeded ${seedTemplates.length} livery templates.`);
    }
  }

  // DriverLivery operations
  async findDriverLiveryById(id: string): Promise<DriverLivery | null> {
    this.logger.debug(`Finding driver livery by id: ${id}`);
    try {
      const livery = this.driverLiveries.get(id) ?? null;
      if (livery) {
        this.logger.info(`Found driver livery: ${id}.`);
      } else {
        this.logger.warn(`Driver livery with id ${id} not found.`);
      }
      return livery;
    } catch (error) {
      this.logger.error(`Error finding driver livery by id ${id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findDriverLiveriesByDriverId(driverId: string): Promise<DriverLivery[]> {
    this.logger.debug(`Finding driver liveries by driver id: ${driverId}`);
    try {
      const liveries = Array.from(this.driverLiveries.values()).filter(l => l.driverId.toString() === driverId);
      this.logger.info(`Found ${liveries.length} driver liveries for driver id: ${driverId}.`);
      return liveries;
    } catch (error) {
      this.logger.error(`Error finding driver liveries by driver id ${driverId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findDriverLiveryByDriverAndCar(driverId: string, carId: string): Promise<DriverLivery | null> {
    this.logger.debug(`Finding driver livery by driver: ${driverId} and car: ${carId}`);
    try {
      for (const livery of this.driverLiveries.values()) {
        if (livery.driverId.toString() === driverId && livery.carId.toString() === carId) {
          this.logger.info(`Found driver livery for driver: ${driverId}, car: ${carId}.`);
          return livery;
        }
      }
      this.logger.warn(`Driver livery for driver ${driverId} and car ${carId} not found.`);
      return null;
    } catch (error) {
      this.logger.error(`Error finding driver livery by driver ${driverId}, car ${carId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findDriverLiveriesByGameId(gameId: string): Promise<DriverLivery[]> {
    this.logger.debug(`Finding driver liveries by game id: ${gameId}`);
    try {
      const liveries = Array.from(this.driverLiveries.values()).filter(l => l.gameId.toString() === gameId);
      this.logger.info(`Found ${liveries.length} driver liveries for game id: ${gameId}.`);
      return liveries;
    } catch (error) {
      this.logger.error(`Error finding driver liveries by game id ${gameId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findDriverLiveryByDriverAndGame(driverId: string, gameId: string): Promise<DriverLivery[]> {
    this.logger.debug(`Finding driver liveries by driver: ${driverId} and game: ${gameId}`);
    try {
      const liveries = Array.from(this.driverLiveries.values()).filter(
        l => l.driverId.toString() === driverId && l.gameId.toString() === gameId
      );
      this.logger.info(`Found ${liveries.length} driver liveries for driver: ${driverId}, game: ${gameId}.`);
      return liveries;
    } catch (error) {
      this.logger.error(`Error finding driver liveries by driver ${driverId}, game ${gameId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async createDriverLivery(livery: DriverLivery): Promise<DriverLivery> {
    this.logger.debug(`Creating driver livery: ${livery.id}`);
    try {
      if (this.driverLiveries.has(livery.id)) {
        this.logger.warn(`DriverLivery with ID ${livery.id} already exists.`);
        throw new Error('DriverLivery with this ID already exists');
      }
      this.driverLiveries.set(livery.id, livery);
      this.logger.info(`DriverLivery ${livery.id} created successfully.`);
      return livery;
    } catch (error) {
      this.logger.error(`Error creating driver livery ${livery.id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async updateDriverLivery(livery: DriverLivery): Promise<DriverLivery> {
    this.logger.debug(`Updating driver livery: ${livery.id}`);
    try {
      if (!this.driverLiveries.has(livery.id)) {
        this.logger.warn(`DriverLivery with ID ${livery.id} not found for update.`);
        throw new Error('DriverLivery not found');
      }
      this.driverLiveries.set(livery.id, livery);
      this.logger.info(`DriverLivery ${livery.id} updated successfully.`);
      return livery;
    } catch (error) {
      this.logger.error(`Error updating driver livery ${livery.id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

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

  // LiveryTemplate operations
  async findTemplateById(id: string): Promise<LiveryTemplate | null> {
    this.logger.debug(`Finding livery template by id: ${id}`);
    try {
      const template = this.templates.get(id) ?? null;
      if (template) {
        this.logger.info(`Found livery template: ${id}.`);
      } else {
        this.logger.warn(`Livery template with id ${id} not found.`);
      }
      return template;
    } catch (error) {
      this.logger.error(`Error finding livery template by id ${id}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findTemplatesBySeasonId(seasonId: string): Promise<LiveryTemplate[]> {
    this.logger.debug(`Finding livery templates by season id: ${seasonId}`);
    try {
      const templates = Array.from(this.templates.values()).filter(t => t.seasonId.toString() === seasonId);
      this.logger.info(`Found ${templates.length} livery templates for season id: ${seasonId}.`);
      return templates;
    } catch (error) {
      this.logger.error(`Error finding livery templates by season id ${seasonId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async findTemplateBySeasonAndCar(seasonId: string, carId: string): Promise<LiveryTemplate | null> {
    this.logger.debug(`Finding livery template by season: ${seasonId} and car: ${carId}`);
    try {
      for (const template of this.templates.values()) {
        if (template.seasonId.toString() === seasonId && template.carId.toString() === carId) {
          this.logger.info(`Found livery template for season: ${seasonId}, car: ${carId}.`);
          return template;
        }
      }
      this.logger.warn(`Livery template for season ${seasonId} and car ${carId} not found.`);
      return null;
    } catch (error) {
      this.logger.error(`Error finding livery template by season ${seasonId}, car ${carId}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async createTemplate(template: LiveryTemplate): Promise<LiveryTemplate> {
    this.logger.debug(`Creating livery template: ${template.id.toString()}`);
    try {
      if (this.templates.has(template.id.toString())) {
        this.logger.warn(`LiveryTemplate with ID ${template.id.toString()} already exists.`);
        throw new Error('LiveryTemplate with this ID already exists');
      }
      this.templates.set(template.id.toString(), template);
      this.logger.info(`LiveryTemplate ${template.id.toString()} created successfully.`);
      return template;
    } catch (error) {
      this.logger.error(`Error creating livery template ${template.id.toString()}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

  async updateTemplate(template: LiveryTemplate): Promise<LiveryTemplate> {
    this.logger.debug(`Updating livery template: ${template.id.toString()}`);
    try {
      if (!this.templates.has(template.id.toString())) {
        this.logger.warn(`LiveryTemplate with ID ${template.id.toString()} not found for update.`);
        throw new Error('LiveryTemplate not found');
      }
      this.templates.set(template.id.toString(), template);
      this.logger.info(`LiveryTemplate ${template.id.toString()} updated successfully.`);
      return template;
    } catch (error) {
      this.logger.error(`Error updating livery template ${template.id.toString()}:`, error instanceof Error ? error : new Error(String(error)));
      throw error;
    }
  }

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

  // Test helpers
  clearDriverLiveries(): void {
    this.logger.debug('Clearing all driver liveries.');
    this.driverLiveries.clear();
    this.logger.info('All driver liveries cleared.');
  }

  clearTemplates(): void {
    this.logger.debug('Clearing all livery templates.');
    this.templates.clear();
    this.logger.info('All livery templates cleared.');
  }

  clear(): void {
    this.logger.debug('Clearing all livery data.');
    this.driverLiveries.clear();
    this.templates.clear();
    this.logger.info('All livery data cleared.');
  }
}