<?php

namespace App\Listeners;

use App\Events\TaskCreated;
use App\Services\TelegramNotificationService;
use Illuminate\Support\Facades\Log;

class SendTelegramTaskNotification
{
    public function handle(TaskCreated $event)
    {
        $task = $event->task;
        $userId = $task->created_by ?? createdBy();

        if (isNotificationTemplateEnabled('Task Created', 'telegram', $userId)) {
            try {
                $telegramService = new TelegramNotificationService($userId);
                $telegramService->sendNotification('Task Created', [
                    '{user_name}' => $task->creator->name ?? 'User',
                    '{task_title}' => $task->title ?? '--',
                    '{project_name}' => $task->project->name ?? 'No Project',
                    '{task_priority}' => $task->priority ?? 'Medium',
                    '{task_due_date}' => $task->due_date ? $task->due_date->format('M d, Y') : 'Not set',
                    '{assigned_to}' => $task->assignedUsers ? $task->assignedUsers->pluck('name')->join(', ') : 'Unassigned',
                    '{app_name}' => config('app.name', 'TaskGo')
                ]);
            } catch (\Exception $e) {
                Log::error("TaskCreated error from telegram listener: " . $e->getMessage());
            }
        }
    }
}