import type { Logger } from '@core/shared/application/Logger';
import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Driver } from '../../domain/entities/Driver';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import {
    UpdateDriverProfileUseCase,
    type UpdateDriverProfileErrorCode,
    type UpdateDriverProfileInput,
} from './UpdateDriverProfileUseCase';

describe('UpdateDriverProfileUseCase', () => {
  let driverRepository: DriverRepository;
  let logger: Logger & { error: ReturnType<typeof vi.fn> };
  let useCase: UpdateDriverProfileUseCase;

  beforeEach(() => {
    driverRepository = {
      findById: vi.fn(),
      update: vi.fn(),
    } as unknown as DriverRepository;

    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger & { error: ReturnType<typeof vi.fn> };

    useCase = new UpdateDriverProfileUseCase(driverRepository, logger);
  });

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

    (driverRepository.findById as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(mockDriver);
    (driverRepository.update as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(mockDriver);

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

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(result.unwrap()).toBeUndefined();

    expect(driverRepository.findById).toHaveBeenCalledWith('driver-1');
    expect((mockDriver.update as unknown as ReturnType<typeof vi.fn>)).toHaveBeenCalledWith({
      bio: 'New bio',
      country: 'US',
    });
    expect(driverRepository.update).toHaveBeenCalled();
  });

  it('returns error when driver not found', async () => {
    (driverRepository.findById as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(null);

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

    const result: Result<void, ApplicationErrorCode<UpdateDriverProfileErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr();
    expect(error.code).toBe('DRIVER_NOT_FOUND');
    expect(error.details?.message).toContain('driver-1');
    });

  it('returns error for invalid profile data', async () => {
    const input: UpdateDriverProfileInput = {
      driverId: 'driver-1',
      bio: '',
    };

    const result: Result<void, ApplicationErrorCode<UpdateDriverProfileErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr();
    expect(error.code).toBe('INVALID_PROFILE_DATA');
    expect(error.details?.message).toBe('Profile data is invalid');
    expect(driverRepository.findById).not.toHaveBeenCalled();
    });

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

    (driverRepository.findById as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(mockDriver);
    (driverRepository.update as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(mockDriver);

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

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect((mockDriver.update as unknown as ReturnType<typeof vi.fn>)).toHaveBeenCalledWith({ country: 'US' });
    });

  it('returns repository error when persistence fails', async () => {
    const mockDriver = {
      id: 'driver-1',
      update: vi.fn().mockReturnValue({ id: 'driver-1' } as Driver),
    } as unknown as Driver;

    (driverRepository.findById as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(mockDriver);
    (driverRepository.update as unknown as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('db error'));

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

    const result: Result<void, ApplicationErrorCode<UpdateDriverProfileErrorCode, { message: string }>> =
      await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const error = result.unwrapErr();
    expect(error.code).toBe('REPOSITORY_ERROR');
    expect(error.details?.message).toBe('db error');

    expect(logger.error).toHaveBeenCalled();
  });
});