<?php

namespace App\Services;

use App\Models\PromptLandingPageAttachment;

class PromptLandingPageHtmlSanitizer
{
    /**
     * Strip any reference to analyzed attachments so they cannot appear on the page.
     *
     * @param  list<PromptLandingPageAttachment>  $attachments
     */
    public function sanitize(string $html, array $attachments = []): string
    {
        $html = (string) preg_replace(
            '/src=(["\'])data:image\/(?:png|jpe?g|gif|webp)[^"\']*\1/i',
            'src=""',
            $html,
        );

        foreach ($this->tokens($attachments) as $token) {
            if ($token === '') {
                continue;
            }

            $html = str_replace($token, '', $html);
            $html = str_replace(e($token), '', $html);
        }

        return $html;
    }

    /**
     * @param  list<PromptLandingPageAttachment>  $attachments
     * @return list<string>
     */
    public function tokens(array $attachments): array
    {
        $tokens = ['prompt-landing-pages/', 'storage/app/private', 'file://'];

        foreach ($attachments as $attachment) {
            $tokens[] = $attachment->path;
            $tokens[] = $attachment->original_name;

            if (filled($attachment->path)) {
                $tokens[] = basename($attachment->path);
            }
        }

        return array_values(array_unique(array_filter($tokens)));
    }
}
