import { z } from "zod";

import { ArticleNotFoundError } from "../../entities/errors/article";
import { articleSchema } from "../../entities/models/article";
import type { IArticlesRepository } from "../repositories/articles.repository.interface";

// ── Input ────────────────────────────────────────────────────────────────
export const getArticleBySlugInputSchema = z
  .object({ slug: z.string().min(1) })
  .strict();
export type GetArticleBySlugInput = z.infer<typeof getArticleBySlugInputSchema>;

// ── Output ───────────────────────────────────────────────────────────────
export const getArticleBySlugOutputSchema = articleSchema;
export type GetArticleBySlugOutput = z.infer<typeof getArticleBySlugOutputSchema>;

// ── Use case ─────────────────────────────────────────────────────────────
export type IGetArticleBySlugUseCase = ReturnType<typeof getArticleBySlugUseCase>;

export const getArticleBySlugUseCase =
  (articlesRepository: IArticlesRepository) =>
  async (input: GetArticleBySlugInput): Promise<GetArticleBySlugOutput> => {
    const article = await articlesRepository.getArticleBySlug(input.slug);
    if (!article) {
      throw new ArticleNotFoundError(`Article with slug "${input.slug}" not found`);
    }
    return getArticleBySlugOutputSchema.parse(article);
  };
