import { describe, it, expect, vi, type Mock } from 'vitest';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import {
  SelectAvatarUseCase,
  type SelectAvatarErrorCode,
  type SelectAvatarInput,
  type SelectAvatarResult,
} from './SelectAvatarUseCase';
import type { IAvatarGenerationRepository } from '../../domain/repositories/IAvatarGenerationRepository';
import { AvatarGenerationRequest } from '../../domain/entities/AvatarGenerationRequest';

interface TestOutputPort extends UseCaseOutputPort<SelectAvatarResult> {
  present: Mock;
  result?: SelectAvatarResult;
}

describe('SelectAvatarUseCase', () => {
  let avatarRepo: { findById: Mock; save: Mock };
  let logger: Logger;
  let output: TestOutputPort;
  let useCase: SelectAvatarUseCase;

  beforeEach(() => {
    avatarRepo = {
      findById: vi.fn(),
      save: vi.fn(),
    };

    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;

    output = {
      present: vi.fn((result: SelectAvatarResult) => {
        output.result = result;
      }),
    } as unknown as TestOutputPort;

    useCase = new SelectAvatarUseCase(
      avatarRepo as unknown as IAvatarGenerationRepository,
      output,
      logger,
    );
  });

  it('returns REQUEST_NOT_FOUND when request does not exist', async () => {
    avatarRepo.findById.mockResolvedValue(null);

    const input: SelectAvatarInput = { requestId: 'missing', selectedIndex: 0 };
    const result = await useCase.execute(input);

    expect(avatarRepo.findById).toHaveBeenCalledWith('missing');
    expect(result).toBeInstanceOf(Result);
    expect(result.isErr()).toBe(true);

    const err = result.unwrapErr() as ApplicationErrorCode<SelectAvatarErrorCode, { message: string }>;
    expect(err.code).toBe('REQUEST_NOT_FOUND');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('returns REQUEST_NOT_COMPLETED when request is not completed', async () => {
    const request = AvatarGenerationRequest.create({
      id: 'req-1',
      userId: 'user-1',
      facePhotoUrl: 'data:image/png;base64,abc',
      suitColor: 'red' as unknown as Parameters<typeof AvatarGenerationRequest.create>[0]['suitColor'],
    });

    avatarRepo.findById.mockResolvedValue(request);

    const input: SelectAvatarInput = { requestId: 'req-1', selectedIndex: 0 };
    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<SelectAvatarErrorCode, { message: string }>;
    expect(err.code).toBe('REQUEST_NOT_COMPLETED');

    expect(avatarRepo.save).not.toHaveBeenCalled();
    expect(output.present).not.toHaveBeenCalled();
  });

  it('selects avatar and presents selected URL when request is completed', async () => {
    const request = AvatarGenerationRequest.create({
      id: 'req-1',
      userId: 'user-1',
      facePhotoUrl: 'data:image/png;base64,abc',
      suitColor: 'red' as unknown as Parameters<typeof AvatarGenerationRequest.create>[0]['suitColor'],
    });
    request.completeWithAvatars(['https://example.com/a.png', 'https://example.com/b.png']);

    avatarRepo.findById.mockResolvedValue(request);

    const input: SelectAvatarInput = { requestId: 'req-1', selectedIndex: 1 };
    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(request.selectedAvatarIndex).toBe(1);
    expect(request.selectedAvatarUrl).toBe('https://example.com/b.png');

    expect(avatarRepo.save).toHaveBeenCalledWith(request);
    expect(output.present).toHaveBeenCalledWith({
      requestId: 'req-1',
      selectedAvatarUrl: 'https://example.com/b.png',
    });
  });

  it('returns REPOSITORY_ERROR when repository throws', async () => {
    avatarRepo.findById.mockRejectedValue(new Error('DB error'));

    const input: SelectAvatarInput = { requestId: 'req-1', selectedIndex: 0 };
    const result = await useCase.execute(input);

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

    expect(output.present).not.toHaveBeenCalled();
    expect((logger.error as unknown as Mock)).toHaveBeenCalled();
  });
});