<?php

namespace FSPoster\App\TelegramNotification\App;

use FSPoster\App\Pages\Settings\Workflow\DTOs\Response\WorkflowActionResponse;
use FSPoster\App\Providers\Common\ShortCodeServiceForWorkflow;
use FSPoster\App\Providers\Common\WorkflowDriver;
use FSPoster\App\Providers\Common\WorkflowDriverInterface;
use FSPoster\App\Providers\Core\Container;
use FSPoster\App\TelegramNotification\App\Services\TelegramNotificationService;

class Driver extends WorkflowDriver implements WorkflowDriverInterface
{
    protected $driver = 'telegram_notification';

    public function __construct()
    {
        $this->setName(fsp__('Send Telegram notification'));
        $this->setEditAction('telegram-notification', 'telegram_notification');
    }

    public function expandItems(array $actionData): array
    {
        $channels = $actionData['channels'] ?? [];

        if (count($channels) <= 1) {
            return empty($channels) ? [] : [$actionData];
        }

        $items = [];
        foreach ($channels as $channelId) {
            $items[] = array_merge($actionData, ['channels' => [$channelId]]);
        }
        return $items;
    }

    public function handle($eventData, WorkflowActionResponse $actionSettings, ShortCodeServiceForWorkflow $shortCodeService): void
    {
        $actionData = $actionSettings->getData();

        if (empty($actionData)) {
            return;
        }

        $channelIds = $actionData['channels'] ?? [];
        $messageTemplate = $actionData['message'] ?? '';

        if (empty($channelIds) || $messageTemplate === '') {
            return;
        }

        $message = $shortCodeService->replace($messageTemplate, $eventData);

        $service = Container::get(TelegramNotificationService::class);
        $service->sendNotification($channelIds, $message);
    }
}
