import { z } from "zod";

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

// ── Input ────────────────────────────────────────────────────────────────
export const createArticleInputSchema = z
  .object({
    title: z.string().min(1).max(255),
    content: z.unknown().optional(),
    authorId: z.string(),
    slug: z.string().optional(),
  })
  .strict();
export type CreateArticleInput = z.infer<typeof createArticleInputSchema>;

// ── Output ───────────────────────────────────────────────────────────────
export const createArticleOutputSchema = articleSchema;
export type CreateArticleOutput = z.infer<typeof createArticleOutputSchema>;

// ── Use case ─────────────────────────────────────────────────────────────
function generateSlug(title: string): string {
  return title
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export type ICreateArticleUseCase = ReturnType<typeof createArticleUseCase>;

export const createArticleUseCase =
  (articlesRepository: IArticlesRepository) =>
  async (input: CreateArticleInput): Promise<CreateArticleOutput> => {
    const now = new Date();
    const article = {
      id: crypto.randomUUID(),
      title: input.title,
      slug: input.slug ?? generateSlug(input.title),
      content: input.content ?? null,
      status: "draft" as const,
      authorId: input.authorId,
      createdAt: now,
      updatedAt: now,
    };
    const result = await articlesRepository.createArticle(article);
    return createArticleOutputSchema.parse(result);
  };
