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 { RaceEventStewardingClosedEvent } from '../../domain/events/RaceEventStewardingClosed';
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: SendFinalResultsUseCase
 *
 * Triggered by RaceEventStewardingClosed domain event.
 * Sends final results modal notifications to all drivers who participated,
 * including any penalty adjustments applied during stewarding.
 */
export class SendFinalResultsUseCase {
  constructor(
    private readonly notificationService: INotificationService,
    private readonly raceEventRepository: IRaceEventRepository,
    private readonly resultRepository: IResultRepository,
  ) {}

  async execute(event: RaceEventStewardingClosedEvent): Promise<Result<void, ApplicationErrorCode<never>>> {
    const { raceEventId, leagueId, driverIds, hadPenaltiesApplied } = 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 final results for the main race session
    const mainRaceSession = raceEvent.getMainRaceSession();
    if (!mainRaceSession) {
      // No main race session, skip
      return Result.ok(undefined);
    }

    const results = await this.resultRepository.findByRaceId(mainRaceSession.id);

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

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

    return Result.ok(undefined);
  }

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

    // Calculate final rating change (could include penalty adjustments)
    const finalRatingChange = this.calculateFinalRatingChange(
      driverResult?.position,
      driverResult?.incidents,
      hadPenaltiesApplied
    );

    const title = `Final Results: ${raceEvent.name}`;
    const body = this.buildFinalResultsBody(
      position,
      positionChange,
      incidents,
      finalRatingChange,
      hadPenaltiesApplied
    );

    await this.notificationService.sendNotification({
      recipientId: driverId,
      type: 'race_final_results' as NotificationType,
      title,
      body,
      channel: 'in_app',
      urgency: 'modal',
      data: {
        raceEventId: raceEvent.id,
        sessionId: raceEvent.getMainRaceSession()?.id ?? '',
        leagueId,
        position,
        positionChange,
        incidents,
        finalRatingChange,
        hadPenaltiesApplied,
      },
      actions: [
        {
          label: 'View Championship Standings',
          type: 'primary',
          href: `/leagues/${leagueId}/standings`,
        },
        {
          label: 'Race Details',
          type: 'secondary',
          href: `/leagues/${leagueId}/races/${raceEvent.id}`,
        },
      ],
      requiresResponse: false, // Can be dismissed, shows final results
    });
  }

  private buildFinalResultsBody(
    position: number | 'DNF',
    positionChange: number,
    incidents: number,
    finalRatingChange: number,
    hadPenaltiesApplied: boolean
  ): 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 = finalRatingChange >= 0 ?
                      `+${finalRatingChange} rating` :
                      `${finalRatingChange} rating`;
    const penaltyText = hadPenaltiesApplied ?
                       ' (including stewarding adjustments)' : '';

    return `Final result: ${positionText} (${positionChangeText} positions). ${incidentsText} ${ratingText}${penaltyText}.`;
  }

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

    // Base calculation (same as provisional)
    const baseChange = position <= 3 ? 25 : position <= 10 ? 10 : -5;
    const positionBonus = Math.max(0, (20 - position) * 2);
    const incidentPenalty = (incidents ?? 0) * -5;

    let finalChange = baseChange + positionBonus + incidentPenalty;

    // Additional penalty adjustments if stewarding applied penalties
    if (hadPenaltiesApplied) {
      // In a real implementation, this would check actual penalties applied
      // For now, we'll assume some penalties might have been applied
      finalChange = Math.max(finalChange - 5, -20); // Cap penalty at -20
    }

    return finalChange;
  }
}