import { MediaReference } from '@core/domain/media/MediaReference';
import type { MediaResolverPort } from '@core/ports/media/MediaResolverPort';
import { GetDriversLeaderboardResult } from '@core/racing/application/use-cases/GetDriversLeaderboardUseCase';
import type { Driver } from '@core/racing/domain/entities/Driver';
import type { SkillLevel } from '@core/racing/domain/services/SkillLevelService';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DriversLeaderboardPresenter } from './DriversLeaderboardPresenter';

describe('DriversLeaderboardPresenter', () => {
  let presenter: DriversLeaderboardPresenter;
  let mockResolver: MediaResolverPort;

  beforeEach(() => {
    mockResolver = {
      resolve: vi.fn().mockImplementation(async (ref) => {
        if (ref.type === 'uploaded') {
          return `/media/uploaded/${ref.mediaId}`;
        }
        if (ref.type === 'generated') {
          // Parse generationRequestId to determine path
          const requestId = ref.generationRequestId;
          if (!requestId) return null;
          
          const firstHyphenIndex = requestId.indexOf('-');
          if (firstHyphenIndex === -1) return null;
          
          const type = requestId.substring(0, firstHyphenIndex);
          const id = requestId.substring(firstHyphenIndex + 1);
          
          if (type === 'driver') {
            return `/media/avatar/${id}`;
          } else if (type === 'team') {
            return `/media/teams/${id}/logo`;
          } else if (type === 'league') {
            return `/media/leagues/${id}/logo`;
          }
          return `/media/generated/${requestId}`;
        }
        if (ref.type === 'system-default') {
          return `/media/default/${ref.variant}`;
        }
        return null;
      }),
    };
    presenter = new DriversLeaderboardPresenter();
    presenter.setMediaResolver(mockResolver);
  });

  describe('present', () => {
    it('should resolve avatarRef to avatarUrl in API response', async () => {
      const coreResult: GetDriversLeaderboardResult = {
        items: [
          {
            driver: {
              id: 'driver-1',
              name: 'Driver One',
              country: 'US',
            } as unknown as Driver,
            rating: 2500,
            skillLevel: 'advanced' as unknown as SkillLevel,
            racesCompleted: 50,
            wins: 10,
            podiums: 20,
            isActive: true,
            rank: 1,
            avatarRef: MediaReference.createUploaded('avatar-1'),
          },
          {
            driver: {
              id: 'driver-2',
              name: 'Driver Two',
              country: 'DE',
            } as unknown as Driver,
            rating: 2400,
            skillLevel: 'intermediate' as unknown as SkillLevel,
            racesCompleted: 40,
            wins: 5,
            podiums: 15,
            isActive: true,
            rank: 2,
            avatarRef: MediaReference.createGenerated('driver-2'),
          },
        ],
        totalRaces: 90,
        totalWins: 15,
        activeCount: 2,
      };

      await presenter.present(coreResult);

      const output = presenter.getResponseModel();

      expect(output.drivers).toHaveLength(2);
      expect(output.drivers[0]).toEqual({
        id: 'driver-1',
        name: 'Driver One',
        rating: 2500,
        skillLevel: 'advanced',
        nationality: 'US',
        racesCompleted: 50,
        wins: 10,
        podiums: 20,
        isActive: true,
        rank: 1,
        avatarUrl: '/media/uploaded/avatar-1',
      });
      expect(output.drivers[1]).toEqual({
        id: 'driver-2',
        name: 'Driver Two',
        rating: 2400,
        skillLevel: 'intermediate',
        nationality: 'DE',
        racesCompleted: 40,
        wins: 5,
        podiums: 15,
        isActive: true,
        rank: 2,
        avatarUrl: '/media/avatar/2',
      });
      expect(output.totalRaces).toBe(90);
      expect(output.totalWins).toBe(15);
      expect(output.activeCount).toBe(2);
    });

    it('should handle missing avatarRef as null avatarUrl', async () => {
      const coreResult: GetDriversLeaderboardResult = {
        items: [
          {
            driver: {
              id: 'driver-1',
              name: 'Driver One',
              country: 'US',
            } as unknown as Driver,
            rating: 2500,
            skillLevel: 'advanced' as unknown as SkillLevel,
            racesCompleted: 50,
            wins: 10,
            podiums: 20,
            isActive: true,
            rank: 1,
            // avatarRef is undefined (not provided)
          },
        ],
        totalRaces: 50,
        totalWins: 10,
        activeCount: 1,
      };

      await presenter.present(coreResult);

      const output = presenter.getResponseModel();

      expect(output.drivers).toHaveLength(1);
      expect(output.drivers[0]!.avatarUrl).toBeNull();
    });

    it('should handle system-default avatarRef', async () => {
      const coreResult: GetDriversLeaderboardResult = {
        items: [
          {
            driver: {
              id: 'driver-1',
              name: 'Driver One',
              country: 'US',
            } as unknown as Driver,
            rating: 2500,
            skillLevel: 'advanced' as unknown as SkillLevel,
            racesCompleted: 50,
            wins: 10,
            podiums: 20,
            isActive: true,
            rank: 1,
            avatarRef: MediaReference.createSystemDefault('avatar'),
          },
        ],
        totalRaces: 50,
        totalWins: 10,
        activeCount: 1,
      };

      await presenter.present(coreResult);

      const output = presenter.getResponseModel();

      expect(output.drivers).toHaveLength(1);
      expect(output.drivers[0]!.avatarUrl).toBe('/media/default/avatar');
    });
  });
});