import { slugify } from "transliteration";
import markdownIt from "../utils/markdown";
import { readMatter } from "../utils/yaml";
import type { Content, Post } from "./types";

export interface FrontmatterData {
  title?: string;
  slug?: string;
  excerpt?: string;
  cover?: string;
  categories?: string[];
  tags?: string[];
  halo?: {
    site?: string;
    name?: string;
    publish?: boolean;
  };
}

export class ContentService {
  renderMarkdown(raw: string): string {
    return markdownIt.render(raw);
  }

  extractFrontmatter(md: string): { frontmatter: FrontmatterData; rawContent: string } {
    const result = readMatter(md);
    const frontmatter = result.data as FrontmatterData;
    const rawContent = result.content;
    return { frontmatter, rawContent };
  }

  buildPostSpec(
    title: string,
    slug: string,
    _raw: string,
    frontmatter: FrontmatterData,
    _content: Content,
  ): Post["spec"] {
    return {
      allowComment: true,
      baseSnapshot: "",
      categories: [],
      cover: frontmatter.cover || "",
      deleted: false,
      excerpt: {
        autoGenerate: !frontmatter.excerpt,
        raw: frontmatter.excerpt || "",
      },
      headSnapshot: "",
      htmlMetas: [],
      owner: "",
      pinned: false,
      priority: 0,
      publish: false,
      publishTime: "",
      releaseSnapshot: "",
      slug: slug || slugify(title, { trim: true }),
      tags: [],
      template: "",
      title,
      visible: "PUBLIC",
    };
  }
}
