<?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;

/**
 * Handler that returns a preview URL for an attachment.
 *
 * Example usage in content:
 * <img src="{{MIRUNI:ATTACHMENT_URL attachment_id=493}}">
 */
class Miruni_Attachment_Url_Preview_Handler extends Miruni_Merge_Handler
{
    public function supports(Miruni_Merge_Action $action): bool
    {
        // @phpstan-ignore identical.alwaysTrue
        return $action === Miruni_Merge_Action::ATTACHMENT_URL;
    }

    /**
     * Return a single string URL for the attachment's objectKey, or an 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 '';
        }

        // Ensure integer id
        $attachment_id = (int) $attachment_id;
        if ($attachment_id <= 0) {
            return '';
        }

        // Use the Miruni service to fetch story attachments by id
        // The service is expected to live in the global Miruni namespace
        if (!class_exists('\Miruni_Service')) {
            error_log('Miruni Attachment Handler: Miruni_Service not available');
            return '';
        }

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

        return $attachment['objectKey'];
    }
}
