<?php

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

use FSPoster\App\Pages\Settings\Workflow\Services\WorkflowEventMetadataRegistry;
use FSPoster\App\Pages\Settings\Workflow\Services\WorkflowService;
use FSPoster\App\Providers\Core\RestRequest;
use RuntimeException;

class WorkflowEventsController
{
    private WorkflowService $service;
    private WorkflowEventMetadataRegistry $metadataRegistry;

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

    public function scheduleFailed(RestRequest $request): array
    {
        $id = $request->param('workflow_id', null, RestRequest::TYPE_INTEGER);
        $networks = $request->param('networks', [], RestRequest::TYPE_ARRAY);
        $channels = $request->param('channels', [], RestRequest::TYPE_ARRAY);
        $channelLabels = $request->param('channelLabels', [], RestRequest::TYPE_ARRAY);
        $offsetSign = $request->param('offset_sign', 'after', RestRequest::TYPE_STRING);
        $offsetValue = $request->param('offset_value', 0, RestRequest::TYPE_INTEGER);
        $offsetType = $request->param('offset_type', 'minute', RestRequest::TYPE_STRING);

        if ($id === null) {
            throw new RuntimeException(fsp__('Workflow id is required.'));
        }

        $meta = $this->metadataRegistry->get('schedule_failed');

        if (!in_array($offsetSign, $meta['allowed_offset_signs'], true)) {
            throw new RuntimeException(fsp__('Invalid offset sign.'));
        }

        if (!in_array($offsetType, ['minute', 'hour', 'day'], true)) {
            throw new RuntimeException(fsp__('Invalid offset type.'));
        }

        $this->service->updateDataById($id, $networks, $channels, $channelLabels, $offsetSign, $offsetValue, $offsetType);

        return [];
    }
}