<?php

namespace FleekDash\Core;

defined('ABSPATH') || exit;

/**
 * Ensures FleekDash thumbnail sizes are generated on upload when auto-regenerate option is enabled.
 */
class ThumbnailRegenerationFilter
{
    public static function filter(array $metadata, int $attachment_id): array
    {
        static $in_progress = false;

        $result = $metadata;

        if ($in_progress || !\get_option('fleekdash_auto_regenerate_thumbnails_on_upload', true)) {
            return $result;
        }

        $has_thumb = isset($metadata['sizes']['fleekdash-thumbnail']);
        $has_preview = isset($metadata['sizes']['fleekdash-preview']);
        if ($has_thumb && $has_preview) {
            return $result;
        }

        $file = \get_attached_file($attachment_id);
        if ($file && \file_exists($file)) {
            $in_progress = true;
            try {
                $new_metadata = \wp_generate_attachment_metadata($attachment_id, $file);
                $result = \is_array($new_metadata) ? $new_metadata : $metadata;
            } finally {
                $in_progress = false;
            }
        }

        return $result;
    }
}
