<?php

namespace App\Domain\Training\Listeners;

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

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

    public function handle(EnrollmentTransferred $event): void
    {
        $oldEnrollment = $event->oldEnrollment;
        $newEnrollment = $event->newEnrollment;
        $participant = $newEnrollment->participant;
        $oldGroup = $oldEnrollment->group;
        $newGroup = $newEnrollment->group;

        $participantName = $participant?->person?->name_ar ?? '';
        $oldGroupName = $oldGroup?->name_ar ?? '';
        $newGroupName = $newGroup?->name_ar ?? '';

        try {
            // Notify guardian
            $this->notificationService->sendSimple(
                type: 'enrollment_transferred',
                recipientId: $participant->id,
                recipientType: 'participant',
                data: [
                    'participant_name' => $participantName,
                    'old_group' => $oldGroupName,
                    'new_group' => $newGroupName,
                    'transfer_date' => now()->format('Y-m-d'),
                ],
            );

            // Notify old group's trainer
            $oldTrainerId = $oldGroup?->head_trainer_id;
            if ($oldTrainerId) {
                $this->notificationService->sendSimple(
                    type: 'participant_transferred_out',
                    recipientId: $oldTrainerId,
                    recipientType: 'user',
                    data: [
                        'participant_name' => $participantName,
                        'old_group' => $oldGroupName,
                        'new_group' => $newGroupName,
                    ],
                );
            }

            // Notify new group's trainer
            $newTrainerId = $newGroup?->head_trainer_id;
            if ($newTrainerId && $newTrainerId !== $oldTrainerId) {
                $this->notificationService->sendSimple(
                    type: 'participant_transferred_in',
                    recipientId: $newTrainerId,
                    recipientType: 'user',
                    data: [
                        'participant_name' => $participantName,
                        'old_group' => $oldGroupName,
                        'new_group' => $newGroupName,
                    ],
                );
            }
        } catch (\Throwable $e) {
            Log::error('Transfer notification failed', [
                'enrollment_id' => $newEnrollment->id,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
