<?php

namespace FSPoster\App\Pages\Settings\Workflow\Services;

use FSPoster\App\Providers\DB\Collection;
use FSPoster\App\Providers\Helpers\Date;

class WorkflowScheduleTimeResolver
{
    private WorkflowEventMetadataRegistry $metadataRegistry;

    public function __construct(WorkflowEventMetadataRegistry $metadataRegistry)
    {
        $this->metadataRegistry = $metadataRegistry;
    }

    public function resolve(Collection $workflow, string $eventKey, array $eventData): int
    {
        $workflowData = json_decode($workflow['data'] ?? '[]', true) ?: [];
        $workflowData = $this->metadataRegistry->applyDefaults($eventKey, $workflowData);
        $offsetSeconds = $this->resolveOffsetSeconds($workflowData);

        return Date::epoch() + $offsetSeconds;
    }

    public function resolveOffsetSeconds(array $workflowData): int
    {
        $offset = (int)($workflowData['offset_value'] ?? 0) * 60;

        if (($workflowData['offset_type'] ?? 'minute') === 'hour') {
            $offset *= 60;
        } elseif (($workflowData['offset_type'] ?? 'minute') === 'day') {
            $offset *= 60 * 24;
        }

        return ($workflowData['offset_sign'] ?? 'after') === 'before' ? -$offset : $offset;
    }
}
