import type { Logger } from '@core/shared/application/Logger';
import { afterEach, beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import { Driver } from '../../domain/entities/Driver';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import {
    CompleteDriverOnboardingUseCase,
    type CompleteDriverOnboardingInput,
} from './CompleteDriverOnboardingUseCase';

describe('CompleteDriverOnboardingUseCase', () => {
  let useCase: CompleteDriverOnboardingUseCase;
  let driverRepository: {
    findById: Mock;
    create: Mock;
  };
  let logger: Logger & { error: Mock };
  let output: { present: Mock } ;

  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2020-01-01T00:00:00.000Z'));
    driverRepository = {
      findById: vi.fn(),
      create: vi.fn(),
    };
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger & { error: Mock };
    output = { present: vi.fn() } as unknown as typeof output;
    useCase = new CompleteDriverOnboardingUseCase(driverRepository as unknown as DriverRepository,
      logger);
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it('should create driver successfully when driver does not exist', async () => {
    const command: CompleteDriverOnboardingInput = {
      userId: 'user-1',
      firstName: 'John',
      lastName: 'Doe',
      displayName: 'John Doe',
      country: 'US',
      bio: 'Test bio',
    };

    driverRepository.findById.mockResolvedValue(null);
    const createdDriver = Driver.create({
      id: 'user-1',
      iracingId: 'user-1',
      name: 'John Doe',
      country: 'US',
      bio: 'Test bio',
    });
    driverRepository.create.mockResolvedValue(createdDriver);

    const result = await useCase.execute(command);

    expect(result.isOk()).toBe(true);
    expect(driverRepository.findById).toHaveBeenCalledWith('user-1');
    expect(driverRepository.create).toHaveBeenCalledWith(
      expect.objectContaining({
        id: 'user-1',
        iracingId: expect.objectContaining({ value: 'user-1' }),
        name: expect.objectContaining({ value: 'John Doe' }),
        country: expect.objectContaining({ value: 'US' }),
        bio: expect.objectContaining({ value: 'Test bio' }),
      })
    );
  });

  it('should return error when driver already exists', async () => {
    const command: CompleteDriverOnboardingInput = {
      userId: 'user-1',
      firstName: 'John',
      lastName: 'Doe',
      displayName: 'John Doe',
      country: 'US',
    };

    const existingDriver = Driver.create({
      id: 'user-1',
      iracingId: 'user-1',
      name: 'John Doe',
      country: 'US',
    });
    driverRepository.findById.mockResolvedValue(existingDriver);

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr().code).toBe('DRIVER_ALREADY_EXISTS');
    expect(driverRepository.create).not.toHaveBeenCalled();
  });

  it('should return error when repository create throws', async () => {
    const command: CompleteDriverOnboardingInput = {
      userId: 'user-1',
      firstName: 'John',
      lastName: 'Doe',
      displayName: 'John Doe',
      country: 'US',
    };

    driverRepository.findById.mockResolvedValue(null);
    driverRepository.create.mockRejectedValue(new Error('DB error'));

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr() as { code: 'REPOSITORY_ERROR'; details?: { message: string } };
    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details?.message).toBe('DB error');
  });

  it('should handle bio being undefined', async () => {
    const command: CompleteDriverOnboardingInput = {
      userId: 'user-1',
      firstName: 'John',
      lastName: 'Doe',
      displayName: 'John Doe',
      country: 'US',
    };

    driverRepository.findById.mockResolvedValue(null);
    const createdDriver = Driver.create({
      id: 'user-1',
      iracingId: 'user-1',
      name: 'John Doe',
      country: 'US',
    });
    driverRepository.create.mockResolvedValue(createdDriver);

    const result = await useCase.execute(command);

    expect(result.isOk()).toBe(true);
    expect(driverRepository.create).toHaveBeenCalledWith(
      expect.objectContaining({
        id: 'user-1',
        iracingId: expect.objectContaining({ value: 'user-1' }),
        name: expect.objectContaining({ value: 'John Doe' }),
        country: expect.objectContaining({ value: 'US' }),
        bio: undefined,
      })
    );
  });
});