<?php

namespace App\Services\Whmcs;

/**
 * Strips markdown markers that WHMCS renders as literal characters (it
 * doesn't process markdown server-side). Used on every body we ship to
 * WHMCS — customer replies, internal admin notes, AI-triage notes — so
 * "**bold**" never appears as a customer-visible / staff-visible
 * "**bold**" string with asterisks. Mirrors the original logic from
 * TicketController::stripMarkdownForWhmcs; consolidated here so the three
 * write paths (manual reply, manual note, AI-generated note) all share it.
 */
class MarkdownCleaner
{
    public static function strip(string $body): string
    {
        // Order matters: triple before double before single — otherwise
        // leftover halves get treated as italic markers in the next pass.
        $body = preg_replace('/\*{3}([^\*\n]+?)\*{3}/u', '$1', $body);
        $body = preg_replace('/\*{2}([^\*\n]+?)\*{2}/u', '$1', $body);
        $body = preg_replace('/(?<![\*\w])\*([^\*\n]+?)\*(?![\*\w])/u', '$1', $body);
        $body = preg_replace('/_{2}([^_\n]+?)_{2}/u', '$1', $body);
        // Headings → plain text.
        $body = preg_replace('/^\s*#{1,6}\s+/m', '', $body);
        // Inline `code` → bare text.
        $body = preg_replace('/`([^`\n]+)`/u', '$1', $body);
        // Fenced code blocks (```bash ... ```) → strip the fence lines,
        // keep the code body intact (otherwise admin would lose the actual
        // command they wanted to share).
        $body = preg_replace('/^\s*```[a-zA-Z0-9_-]*\s*\n?/m', '', $body);
        $body = preg_replace('/^\s*```\s*$/m', '', $body);
        // [text](url) → "text (url)" so the URL stays visible.
        $body = preg_replace('/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/u', '$1 ($2)', $body);
        return $body;
    }
}
