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

describe('GetMediaUseCase', () => {
  let mediaRepo: {
    findById: Mock;
  };
  let logger: Logger;
  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;

    useCase = new GetMediaUseCase(
      mediaRepo as unknown as MediaRepository,
      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');
  });

  it('returns GetMediaResult 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');

    const successResult = result.unwrap();
    expect(successResult).toEqual({
      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');
  });
});