import { describe, it, expect, vi, Mocked } from 'vitest';
import { LeagueWizardService } from './LeagueWizardService';
import { LeagueWizardCommandModel } from '@/lib/command-models/leagues/LeagueWizardCommandModel';
import { apiClient } from '@/lib/apiClient';

// Mock the apiClient
vi.mock('@/lib/apiClient', () => ({
  apiClient: {
    leagues: {
      create: vi.fn(),
    },
  },
}));

describe('LeagueWizardService', () => {
  describe('createLeague', () => {
    it('should call apiClient.leagues.create with correct command', async () => {
      const form = {
        name: 'Test League',
        description: 'A test league',
        toCreateLeagueCommand: vi.fn().mockReturnValue({
          name: 'Test League',
          description: 'A test league',
          ownerId: 'owner-123',
        }),
      } as unknown as LeagueWizardCommandModel;

      const ownerId = 'owner-123';
      const mockOutput = { leagueId: 'new-league-id', success: true };

      (apiClient.leagues.create as any).mockResolvedValue(mockOutput);

      const result = await LeagueWizardService.createLeague(form, ownerId);

      expect(form.toCreateLeagueCommand).toHaveBeenCalledWith(ownerId);
      expect(apiClient.leagues.create).toHaveBeenCalledWith({
        name: 'Test League',
        description: 'A test league',
        ownerId: 'owner-123',
      });
      expect(result).toEqual(mockOutput);
    });

    it('should throw error when apiClient.leagues.create fails', async () => {
      const form = {
        name: 'Test League',
        description: 'A test league',
        toCreateLeagueCommand: vi.fn().mockReturnValue({
          name: 'Test League',
          description: 'A test league',
          ownerId: 'owner-123',
        }),
      } as unknown as LeagueWizardCommandModel;

      const ownerId = 'owner-123';
      const error = new Error('API call failed');

      (apiClient.leagues.create as Mocked<typeof apiClient.leagues.create>).mockRejectedValue(error);

      await expect(LeagueWizardService.createLeague(form, ownerId)).rejects.toThrow('API call failed');
    });
  });

  describe('createLeagueFromConfig', () => {
    it('should call createLeague with same parameters', async () => {
      const form = {
        name: 'Test League',
        description: 'A test league',
        toCreateLeagueCommand: vi.fn().mockReturnValue({
          name: 'Test League',
          description: 'A test league',
          ownerId: 'owner-123',
        }),
      } as unknown as LeagueWizardCommandModel;

      const ownerId = 'owner-123';
      const mockOutput = { leagueId: 'new-league-id', success: true };

      (apiClient.leagues.create as Mocked<typeof apiClient.leagues.create>).mockResolvedValue(mockOutput);

      const result = await LeagueWizardService.createLeagueFromConfig(form, ownerId);

      expect(apiClient.leagues.create).toHaveBeenCalled();
      expect(result).toEqual(mockOutput);
    });
  });
});