import { describe, it, expect, vi, type Mock } from 'vitest';
import {
  GetMediaUseCase,
  type GetMediaInput,
  type GetMediaResult,
  type GetMediaErrorCode,
} from './GetMediaUseCase';
import type { IMediaRepository } from '../../domain/repositories/IMediaRepository';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import { Media } from '../../domain/entities/Media';

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

describe('GetMediaUseCase', () => {
  let mediaRepo: {
    findById: Mock;
  };
  let logger: Logger;
  let output: TestOutputPort;
  let useCase: GetMediaUseCase;

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

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

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

    useCase = new GetMediaUseCase(
      mediaRepo as unknown as IMediaRepository,
      output,
      logger,
    );
  });

  it('returns MEDIA_NOT_FOUND when media is not found', async () => {
    mediaRepo.findById.mockResolvedValue(null);

    const input: GetMediaInput = { mediaId: 'missing' };
    const result = await useCase.execute(input);

    expect(mediaRepo.findById).toHaveBeenCalledWith('missing');
    expect(result).toBeInstanceOf(Result);
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<GetMediaErrorCode, { message: string }>;
    expect(err.code).toBe('MEDIA_NOT_FOUND');
    expect(output.present).not.toHaveBeenCalled();
  });

  it('presents media details when media exists', async () => {
    const media = Media.create({
      id: 'media-1',
      filename: 'file.png',
      originalName: 'file.png',
      mimeType: 'image/png',
      size: 123,
      url: 'https://example.com/file.png',
      type: 'image',
      uploadedBy: 'user-1',
    });

    mediaRepo.findById.mockResolvedValue(media);

    const input: GetMediaInput = { mediaId: 'media-1' };
    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    expect(mediaRepo.findById).toHaveBeenCalledWith('media-1');
    expect(output.present).toHaveBeenCalledWith({
      media: {
        id: media.id,
        filename: media.filename,
        originalName: media.originalName,
        mimeType: media.mimeType,
        size: media.size,
        url: media.url.value,
        type: media.type,
        uploadedBy: media.uploadedBy,
        uploadedAt: media.uploadedAt,
        metadata: media.metadata,
      },
    });
  });

  it('handles repository errors by returning REPOSITORY_ERROR', async () => {
    mediaRepo.findById.mockRejectedValue(new Error('DB error'));

    const input: GetMediaInput = { mediaId: 'media-1' };
    const result = await useCase.execute(input);

    expect((logger.error as unknown as Mock)).toHaveBeenCalled();
    expect(result.isErr()).toBe(true);
    const err = result.unwrapErr() as ApplicationErrorCode<GetMediaErrorCode, { message: string }>;
    expect(err.code).toBe('REPOSITORY_ERROR');
  });
});
