import { describe, it, expect, vi } from 'vitest';
import { UpdateDriverProfileUseCase } from './UpdateDriverProfileUseCase';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import { EntityMappers } from '../mappers/EntityMappers';

vi.mock('../mappers/EntityMappers', () => ({
  EntityMappers: {
    toDriverDTO: vi.fn(),
  },
}));

describe('UpdateDriverProfileUseCase', () => {
  it('updates driver profile successfully', async () => {
    const mockDriver = {
      id: 'driver-1',
      update: vi.fn().mockReturnValue({}),
    };

    const mockUpdatedDriver = {};

    const mockDTO = { id: 'driver-1', bio: 'New bio' };

    const mockDriverRepository = {
      findById: vi.fn().mockResolvedValue(mockDriver),
      update: vi.fn().mockResolvedValue(mockUpdatedDriver),
    } as unknown as IDriverRepository;

    (EntityMappers.toDriverDTO as any).mockReturnValue(mockDTO);

    const useCase = new UpdateDriverProfileUseCase(mockDriverRepository);

    const input = {
      driverId: 'driver-1',
      bio: 'New bio',
      country: 'US',
    };

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toEqual(mockDTO);
    expect(mockDriverRepository.findById).toHaveBeenCalledWith('driver-1');
    expect(mockDriver.update).toHaveBeenCalledWith({ bio: 'New bio', country: 'US' });
    expect(mockDriverRepository.update).toHaveBeenCalledWith({});
    expect(EntityMappers.toDriverDTO).toHaveBeenCalledWith(mockUpdatedDriver);
  });

  it('returns error when driver not found', async () => {
    const mockDriverRepository = {
      findById: vi.fn().mockResolvedValue(null),
    } as unknown as IDriverRepository;

    const useCase = new UpdateDriverProfileUseCase(mockDriverRepository);

    const input = {
      driverId: 'driver-1',
      bio: 'New bio',
    };

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({ code: 'DRIVER_NOT_FOUND' });
  });

  it('updates only provided fields', async () => {
    const mockDriver = {
      id: 'driver-1',
      update: vi.fn().mockReturnValue({}),
    };

    const mockUpdatedDriver = {};

    const mockDTO = { id: 'driver-1', country: 'US' };

    const mockDriverRepository = {
      findById: vi.fn().mockResolvedValue(mockDriver),
      update: vi.fn().mockResolvedValue(mockUpdatedDriver),
    } as unknown as IDriverRepository;

    (EntityMappers.toDriverDTO as any).mockReturnValue(mockDTO);

    const useCase = new UpdateDriverProfileUseCase(mockDriverRepository);

    const input = {
      driverId: 'driver-1',
      country: 'US',
    };

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(mockDriver.update).toHaveBeenCalledWith({ country: 'US' });
  });
});