/**
 * Blog Management Sanitizers
 * XSS prevention and data sanitization for blog content
 */

import DOMPurify from 'isomorphic-dompurify';
import type { CreateBlogPostInput, UpdateBlogPostInput } from '@/lib/types/blog-management.types';

/**
 * Sanitize blog title
 * Removes HTML tags and dangerous characters
 */
export function sanitizeTitle(title: string): string {
  return DOMPurify.sanitize(title, {
    ALLOWED_TAGS: [], // No HTML tags in titles
    ALLOWED_ATTR: [],
  }).trim();
}

/**
 * Sanitize blog excerpt
 * Allows basic formatting tags only
 */
export function sanitizeExcerpt(excerpt: string): string {
  return DOMPurify.sanitize(excerpt, {
    ALLOWED_TAGS: ['em', 'strong', 'b', 'i'], // Basic emphasis only
    ALLOWED_ATTR: [],
  }).trim();
}

/**
 * Sanitize blog content
 * Allows rich text formatting but removes dangerous elements
 */
export function sanitizeContent(content: string): string {
  return DOMPurify.sanitize(content, {
    ALLOWED_TAGS: [
      // Text formatting
      'p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
      'strong', 'em', 'b', 'i', 'u', 'mark', 'del', 'ins',
      'blockquote', 'pre', 'code',
      // Lists
      'ul', 'ol', 'li',
      // Links
      'a',
      // Media
      'img', 'figure', 'figcaption',
      // Tables
      'table', 'thead', 'tbody', 'tr', 'th', 'td',
      // Semantic
      'div', 'span', 'section', 'article',
    ],
    ALLOWED_ATTR: [
      'href', 'title', 'target', 'rel',
      'src', 'alt', 'width', 'height',
      'class', 'id',
    ],
    ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
  }).trim();
}

/**
 * Sanitize author name
 */
export function sanitizeAuthor(author: string): string {
  return DOMPurify.sanitize(author, {
    ALLOWED_TAGS: [],
    ALLOWED_ATTR: [],
  }).trim();
}

/**
 * Sanitize tag
 */
export function sanitizeTag(tag: string): string {
  return DOMPurify.sanitize(tag, {
    ALLOWED_TAGS: [],
    ALLOWED_ATTR: [],
  })
    .trim()
    .toLowerCase();
}

/**
 * Sanitize tags array
 */
export function sanitizeTags(tags: string[] | undefined): string[] {
  if (!tags || !Array.isArray(tags)) return [];

  return tags
    .map(sanitizeTag)
    .filter((tag) => tag.length > 0 && tag.length <= 50)
    .slice(0, 10); // Max 10 tags
}

/**
 * Sanitize meta keywords
 */
export function sanitizeMetaKeywords(keywords: string[] | undefined): string[] {
  if (!keywords || !Array.isArray(keywords)) return [];

  return keywords
    .map((kw) =>
      DOMPurify.sanitize(kw, {
        ALLOWED_TAGS: [],
        ALLOWED_ATTR: [],
      }).trim()
    )
    .filter((kw) => kw.length > 0 && kw.length <= 50)
    .slice(0, 15); // Max 15 keywords
}

/**
 * Sanitize create blog post input
 */
export function sanitizeCreateBlogPostInput(input: CreateBlogPostInput): CreateBlogPostInput {
  return {
    slug: input.slug.trim().toLowerCase(),
    lang: input.lang,
    title: sanitizeTitle(input.title),
    excerpt: sanitizeExcerpt(input.excerpt),
    content: sanitizeContent(input.content),
    author: sanitizeAuthor(input.author),
    tags: sanitizeTags(input.tags),
    status: input.status,
    featured: input.featured,
    featured_order: input.featured_order,
    meta_title: input.meta_title ? sanitizeTitle(input.meta_title) : undefined,
    meta_description: input.meta_description
      ? sanitizeExcerpt(input.meta_description)
      : undefined,
    meta_keywords: sanitizeMetaKeywords(input.meta_keywords),
    date: input.date,
    generateAiImage: input.generateAiImage,
  };
}

/**
 * Sanitize update blog post input
 */
export function sanitizeUpdateBlogPostInput(input: UpdateBlogPostInput): UpdateBlogPostInput {
  const sanitized: UpdateBlogPostInput = {};

  if (input.slug !== undefined) sanitized.slug = input.slug.trim().toLowerCase();
  if (input.title !== undefined) sanitized.title = sanitizeTitle(input.title);
  if (input.excerpt !== undefined) sanitized.excerpt = sanitizeExcerpt(input.excerpt);
  if (input.content !== undefined) sanitized.content = sanitizeContent(input.content);
  if (input.author !== undefined) sanitized.author = sanitizeAuthor(input.author);
  if (input.tags !== undefined) sanitized.tags = sanitizeTags(input.tags);
  if (input.status !== undefined) sanitized.status = input.status;
  if (input.featured !== undefined) sanitized.featured = input.featured;
  if (input.featured_order !== undefined) sanitized.featured_order = input.featured_order;
  if (input.meta_title !== undefined) sanitized.meta_title = sanitizeTitle(input.meta_title);
  if (input.meta_description !== undefined)
    sanitized.meta_description = sanitizeExcerpt(input.meta_description);
  if (input.meta_keywords !== undefined)
    sanitized.meta_keywords = sanitizeMetaKeywords(input.meta_keywords);
  if (input.date !== undefined) sanitized.date = input.date;
  if (input.published_at !== undefined) sanitized.published_at = input.published_at;
  if (input.cover_image !== undefined) sanitized.cover_image = input.cover_image;
  if (input.regenerateAiImage !== undefined) sanitized.regenerateAiImage = input.regenerateAiImage;

  return sanitized;
}
