import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { INotificationService } from '../../../notifications/application/ports/INotificationService';
import type { IRaceEventRepository } from '../../domain/repositories/IRaceEventRepository';
import type { IResultRepository } from '../../domain/repositories/IResultRepository';
import type { MainRaceCompletedEvent } from '../../domain/events/MainRaceCompleted';
import type { NotificationType } from '../../../notifications/domain/types/NotificationTypes';
import type { RaceEvent } from '../../domain/entities/RaceEvent';
import type { Result as RaceResult } from '../../domain/entities/Result';

/**
 * Use Case: SendPerformanceSummaryUseCase
 *
 * Triggered by MainRaceCompleted domain event.
 * Sends immediate performance summary modal notifications to all drivers who participated in the main race.
 */
export class SendPerformanceSummaryUseCase {
  constructor(
    private readonly notificationService: INotificationService,
    private readonly raceEventRepository: IRaceEventRepository,
    private readonly resultRepository: IResultRepository,
  ) {}

  async execute(event: MainRaceCompletedEvent): Promise<Result<void, ApplicationErrorCode<never>>> {
    const { raceEventId, sessionId, leagueId, driverIds } = event.eventData;

    // Get race event to include context
    const raceEvent = await this.raceEventRepository.findById(raceEventId);
    if (!raceEvent) {
      // RaceEvent not found, skip
      return Result.ok(undefined);
    }

    // Get results for the main race session to calculate performance data
    const results = await this.resultRepository.findByRaceId(sessionId);

    // Send performance summary to each participating driver
    for (const driverId of driverIds) {
      const driverResult = results.find(r => r.driverId === driverId);

      await this.sendPerformanceSummaryNotification(
        driverId,
        raceEvent,
        driverResult,
        leagueId
      );
    }

    return Result.ok(undefined);
  }

  private async sendPerformanceSummaryNotification(
    driverId: string,
    raceEvent: RaceEvent,
    driverResult: RaceResult | undefined,
    leagueId: string
  ): Promise<void> {
    const position = driverResult?.position ?? 'DNF';
    const positionChange = driverResult?.getPositionChange() ?? 0;
    const incidents = driverResult?.incidents ?? 0;

    // Calculate provisional rating change (simplified version)
    const provisionalRatingChange = this.calculateProvisionalRatingChange(
      driverResult?.position,
      driverResult?.incidents
    );

    const title = `Race Complete: ${raceEvent.name}`;
    const body = this.buildPerformanceSummaryBody(
      position,
      positionChange,
      incidents,
      provisionalRatingChange
    );

    await this.notificationService.sendNotification({
      recipientId: driverId,
      type: 'race_performance_summary' as NotificationType,
      title,
      body,
      channel: 'in_app',
      urgency: 'modal',
      data: {
        raceEventId: raceEvent.id,
        sessionId: raceEvent.getMainRaceSession()?.id ?? '',
        leagueId,
        position,
        positionChange,
        incidents,
        provisionalRatingChange,
      },
      actions: [
        {
          label: 'View Full Results',
          type: 'primary',
          href: `/leagues/${leagueId}/races/${raceEvent.id}`,
        },
      ],
      requiresResponse: false, // Can be dismissed, but shows performance data
    });
  }

  private buildPerformanceSummaryBody(
    position: number | 'DNF',
    positionChange: number,
    incidents: number,
    provisionalRatingChange: number
  ): string {
    const positionText = position === 'DNF' ? 'DNF' : `P${position}`;
    const positionChangeText = positionChange > 0 ? `+${positionChange}` :
                              positionChange < 0 ? `${positionChange}` : '±0';
    const incidentsText = incidents === 0 ? 'Clean race!' : `${incidents} incident${incidents > 1 ? 's' : ''}`;
    const ratingText = provisionalRatingChange >= 0 ?
                      `+${provisionalRatingChange} rating` :
                      `${provisionalRatingChange} rating`;

    return `You finished ${positionText} (${positionChangeText} positions). ${incidentsText} Provisional ${ratingText}.`;
  }

  private calculateProvisionalRatingChange(position?: number, incidents?: number): number {
    if (!position) return -10; // DNF penalty

    // Simplified rating calculation (matches existing GetRaceDetailUseCase logic)
    const baseChange = position <= 3 ? 25 : position <= 10 ? 10 : -5;
    const positionBonus = Math.max(0, (20 - position) * 2);
    const incidentPenalty = (incidents ?? 0) * -5;

    return baseChange + positionBonus + incidentPenalty;
  }
}