import { describe, it, expect } from "vitest";
import { ZodError } from "zod";
import {
  getArticleBySlugUseCase,
  getArticleBySlugOutputSchema,
} from "@/application/use-cases/get-article-by-slug.use-case";
import { MockArticlesRepository } from "@/infrastructure/repositories/articles.repository.mock";
import { ArticleNotFoundError } from "@/entities/errors/article";
import { articleFactory } from "@/__factories__/article.factory";
import type { IArticlesRepository } from "@/application/repositories/articles.repository.interface";

describe("getArticleBySlugUseCase", () => {
  it("returns the article when slug exists", async () => {
    const repo = new MockArticlesRepository();
    const seed = articleFactory.build({ slug: "test-slug" });
    await repo.createArticle(seed);

    const useCase = getArticleBySlugUseCase(repo);
    const result = await useCase({ slug: "test-slug" });

    expect(result?.slug).toBe("test-slug");
  });

  it("throws ArticleNotFoundError when slug is missing", async () => {
    const repo = new MockArticlesRepository();
    const useCase = getArticleBySlugUseCase(repo);
    await expect(useCase({ slug: "does-not-exist" })).rejects.toThrow(
      ArticleNotFoundError,
    );
  });
});

describe("getArticleBySlugUseCase output validation", () => {
  it("throws when repository returns a malformed article", async () => {
    const repo = {
      getArticleBySlug: async () => ({ id: 123 }) as unknown as never,
    } as unknown as IArticlesRepository;
    const useCase = getArticleBySlugUseCase(repo);
    await expect(useCase({ slug: "test" })).rejects.toBeInstanceOf(ZodError);
  });

  it("exports an output schema that accepts a valid article shape", () => {
    expect(getArticleBySlugOutputSchema).toBeDefined();
    const result = getArticleBySlugOutputSchema.safeParse({
      id: "a1",
      title: "Test",
      slug: "test",
      content: null,
      status: "draft",
      authorId: "u1",
      createdAt: new Date(),
      updatedAt: new Date(),
    });
    expect(result.success).toBe(true);
  });
});
