import { describe, it, expect } from "vitest";
import { ZodError } from "zod";
import {
  getMediaUseCase,
  getMediaOutputSchema,
} from "@/application/use-cases/get-media.use-case";
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
import { MediaNotFoundError } from "@/entities/errors/media";
import { mediaFactory } from "@/__factories__/media.factory";

describe("getMediaUseCase", () => {
  it("returns media when found", async () => {
    const repo = new MockMediaRepository();
    const seed = mediaFactory.build({ id: "m-1" });
    await repo._store(seed);

    const useCase = getMediaUseCase(repo);
    const result = await useCase({ id: "m-1" });

    expect(result.id).toBe("m-1");
    expect(result.alt).toBe(seed.alt);
  });

  it("throws MediaNotFoundError when id does not exist", async () => {
    const repo = new MockMediaRepository();
    const useCase = getMediaUseCase(repo);

    await expect(useCase({ id: "missing" })).rejects.toThrow(
      MediaNotFoundError,
    );
  });

  it("parses valid output without error", async () => {
    const validMedia = mediaFactory.build({ id: "m-r25" });
    expect(() => getMediaOutputSchema.parse(validMedia)).not.toThrow();
  });

  it("throws ZodError when repository returns malformed media", async () => {
    const repo = new MockMediaRepository();
    // Store a malformed object (missing required fields) via type cast
    await repo._store({ id: "bad", alt: "alt", url: "u" } as never);

    const useCase = getMediaUseCase(repo);
    await expect(useCase({ id: "bad" })).rejects.toBeInstanceOf(ZodError);
  });
});
