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

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

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

    output = {
      present: vi.fn(),
    } as unknown as UseCaseOutputPort<UpdateDriverProfileResult> & { present: ReturnType<typeof vi.fn> };

    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, output);
  });

  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();

    expect(output.present).toHaveBeenCalledTimes(1);
    const presentedRaw = output.present.mock.calls[0]?.[0];
    expect(presentedRaw).toBeDefined();
    expect(presentedRaw).toEqual({ id: 'driver-1' });
  });

  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');
    expect(output.present).not.toHaveBeenCalled();
  });

  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();
    expect(output.present).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' });
    expect(output.present).toHaveBeenCalledTimes(1);
  });

  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(output.present).not.toHaveBeenCalled();
    expect(logger.error).toHaveBeenCalled();
  });
});