import { readCms, slugify, writeCms, type Post, type PostStatus } from './cms';

export type PublishPostInput = {
  title: string;
  category?: string;
  time?: string;
  readTime?: string;
  excerpt?: string;
  body?: string[] | string;
  status?: PostStatus;
  slug?: string;
  image?: string;
  thumbnail?: string;
  urgent?: boolean;
  sidebar?: boolean;
  sourceUrl?: string;
  publishedAt?: string;
};

export const publishPost = async (input: PublishPostInput) => {
  const cms = await readCms();
  const title = input.title.trim();
  const slug = slugify(input.slug || title);

  if (!title || !slug) {
    throw new Error('title is required');
  }

  const body = Array.isArray(input.body)
    ? input.body
    : String(input.body ?? '').split(/\n\s*\n/).map((item) => item.trim()).filter(Boolean);

  const existingIndex = cms.posts.findIndex((item) => item.slug === slug);
  const existing = existingIndex >= 0 ? cms.posts[existingIndex] : undefined;

  const post: Post = {
    slug,
    title,
    category: input.category || cms.categories[0] || 'عمومی',
    time: input.time || 'هم‌اکنون',
    readTime: input.readTime || '۳ دقیقه',
    excerpt: input.excerpt || body[0] || '',
    body,
    status: input.status || 'pending',
    image: input.image || undefined,
    thumbnail: input.thumbnail || undefined,
    urgent: input.urgent ?? false,
    sidebar: input.sidebar ?? false,
    sourceUrl: input.sourceUrl || undefined,
    publishedAt: input.publishedAt || existing?.publishedAt || new Date().toISOString(),
  };

  if (existingIndex >= 0) {
    cms.posts[existingIndex] = post;
  } else {
    cms.posts.unshift(post);
  }

  if (!cms.categories.includes(post.category)) {
    cms.categories.push(post.category);
  }

  await writeCms(cms);

  return post;
};
