<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Content;

/**
 * Resolve a storefront-facing thumbnail URL for a post.
 *
 * Order: featured image → first inline content image → filter hook.
 */
final class ThumbnailUrl
{
    public static function forPost(int $post_id, string $size = 'thumbnail'): string
    {
        if ($post_id <= 0) {
            return '';
        }

        $url = '';
        if (function_exists('get_the_post_thumbnail_url')) {
            foreach (array_unique([$size, 'medium', 'large', 'full']) as $trySize) {
                $candidate = (string) get_the_post_thumbnail_url($post_id, $trySize);
                if ($candidate !== '') {
                    $url = $candidate;
                    break;
                }
            }
        }

        if ($url === '') {
            $url = self::firstInlineImage($post_id);
        }

        if (function_exists('apply_filters')) {
            /** @var mixed $filtered */
            $filtered = apply_filters('seekmodo_thumbnail_url', $url, $post_id, $size);
            if (is_string($filtered)) {
                $url = $filtered;
            }
        }

        return $url;
    }

    private static function firstInlineImage(int $post_id): string
    {
        if (!function_exists('get_post')) {
            return '';
        }
        $post = get_post($post_id);
        if (!$post || !isset($post->post_content)) {
            return '';
        }
        $content = (string) $post->post_content;
        if ($content === '') {
            return '';
        }
        if (!preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $content, $m)) {
            return '';
        }
        $src = trim((string) ($m[1] ?? ''));
        if ($src === '' || stripos($src, 'data:') === 0) {
            return '';
        }

        return $src;
    }
}
