import { slugify } from './slug';
import { sanitizeHtml } from './sanitize';
import { CATEGORIES } from './blog-const';

export function parsePostBody(data: Record<string, unknown>) {
  const title = String(data.title ?? '').trim();
  if (!title) return { error: 'Il titolo è obbligatorio.' } as const;
  const category = String(data.category ?? '');
  if (!(CATEGORIES as readonly string[]).includes(category)) return { error: 'Categoria non valida.' } as const;
  const slug = slugify(String(data.slug ?? '') || title);
  if (!slug) return { error: 'Slug non valido.' } as const;
  return {
    value: {
      title, slug, category,
      excerpt: String(data.excerpt ?? '').trim().slice(0, 300),
      body_html: sanitizeHtml(String(data.body_html ?? '')),
      cover: data.cover ? String(data.cover) : null,
      draft: Boolean(data.draft),
    },
  } as const;
}
