<?php

namespace App\Domain\Training\Listeners;

use App\Domain\Training\Events\EvaluationShared;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class SendEvaluationSharedNotification implements ShouldQueue
{
    public function __construct(
        private NotificationService $notificationService,
    ) {}

    public function handle(EvaluationShared $event): void
    {
        try {
            $participant = $event->evaluation->participant;

            $this->notificationService->sendSimple(
                type: 'evaluation_shared',
                recipientId: $participant->id,
                recipientType: 'participant',
                data: [
                    'participant_name' => $participant->person?->full_name ?? '',
                    'evaluation_title' => $event->evaluation->title ?? $event->evaluation->name ?? '',
                    'trainer_name' => $event->actor->name,
                    'evaluation_date' => $event->evaluation->evaluation_date?->format('Y-m-d') ?? now()->format('Y-m-d'),
                ],
            );
        } catch (\Throwable $e) {
            Log::error('SendEvaluationSharedNotification failed: ' . $e->getMessage(), [
                'evaluation_id' => $event->evaluation->id,
            ]);
        }
    }

    public function failed(EvaluationShared $event, \Throwable $exception): void
    {
        Log::critical('SendEvaluationSharedNotification PERMANENTLY FAILED', [
            'evaluation_id' => $event->evaluation->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
