<?php

namespace Miruni\Merge_Syntax\Handlers;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

use Miruni\Merge_Syntax\Miruni_Merge_Action;
use Miruni\Merge_Syntax\Miruni_Merge_SyntaxOperation;
use Miruni\Merge_Syntax\Miruni_Merge_Handler;
use Miruni\Miruni_Media_Manager;

/**
 * Publish-time handler that uploads a Miruni attachment to the WP media library
 * and returns the resulting media URL.
 *
 * Usage in content during publish: {{MIRUNI:ATTACHMENT_URL attachment_id=493}}
 */
class Miruni_Attachment_Url_Publish_Handler extends Miruni_Merge_Handler
{
    public function supports(Miruni_Merge_Action $action): bool
    {
        // @phpstan-ignore identical.alwaysTrue
        return $action === Miruni_Merge_Action::ATTACHMENT_URL;
    }

    /**
     * Upload the referenced attachment to the media gallery and return the URL.
     * Returns empty string on failure.
     *
     * @param Miruni_Merge_SyntaxOperation $operation
     * @param array<string,mixed> $context
     * @return string
     */
    protected function handle(Miruni_Merge_SyntaxOperation $operation, array $context = []): string
    {
        $attachment_id = $this->arg($operation, 'attachment_id', null);

        if ($attachment_id === null) {
            return '';
        }

        $attachment_id = (int) $attachment_id;
        if ($attachment_id <= 0) {
            return '';
        }

        if (!class_exists('\Miruni_Service')) {
            error_log('Miruni Attachment Publish Handler: Miruni_Service not available');
            return '';
        }

        if (!class_exists('\Miruni_Media_Manager')) {
            error_log('Miruni Attachment Publish Handler: Miruni_Media_Manager not available');
            return '';
        }

        try {
            $miruni = new \Miruni_Service();
            $attachments = $miruni->get_story_attachments_by_ids([$attachment_id]);

            $attachment = $attachments[0];

            if (empty($attachment['objectKey'])) {
                return '';
            }

            // Attempt to upload the remote URL to WP media. The media manager is
            // expected to return an attachment ID on success.
            $upload_id = Miruni_Media_Manager::upload_from_url($attachment['objectKey']);

            if (!is_int($upload_id) || $upload_id <= 0) {
                error_log('Miruni Attachment Publish Handler: upload_from_url failed for attachment ' . $attachment_id);
                return '';
            }

            // Get the URL for the newly uploaded attachment
            $url = wp_get_attachment_url($upload_id);
            if (!is_string($url) || $url === '') {
                error_log('Miruni Attachment Publish Handler: wp_get_attachment_url returned empty for upload id ' . $upload_id);
                return '';
            }

            return $url;
        } catch (\Throwable $e) {
            error_log('Miruni Attachment Publish Handler: exception while processing attachment ' . $attachment_id . ' - ' . $e->getMessage());
            return '';
        }
    }
}
