<?php

namespace App\Listeners;

use App\Jobs\SendReservationCancelledMail;
use App\Models\MessageSetting;
use Cog\Laravel\Love\Reaction\Events\ReactionHasBeenRemoved;
use Illuminate\Support\Facades\Log;

class ReactionRemovedListener
{
    public function handle(ReactionHasBeenRemoved $event)
    {

        $reaction = $event->getReaction();
        $reactionType = $reaction->getType()->getName();
        $recipient = $reaction->getReactant()->getReactable();

        // Get message settings for this recipient
        $messageSetting = MessageSetting::where('message_settingable_id', $recipient->id)
            ->where('message_settingable_type', get_class($recipient))
            ->first();

        $sendCancellationEmail = false;

        // Check reaction type and corresponding message setting
        if ($reactionType === 'Reserve') {
            // For Reserve reactions, check system_message setting
            $sendCancellationEmail = $messageSetting ? $messageSetting->system_message : true; // Default to true
        }

        Log::info('ReactionRemovedListener', [
            'reaction_type' => $reactionType,
            'recipient_id' => $recipient->id,
            'recipient_type' => get_class($recipient),
            'sendCancellationEmail' => $sendCancellationEmail,
        ]);

        if ($sendCancellationEmail && $reactionType === 'Reserve') {
            // Extract data before reaction is deleted
            $reacter = $reaction->getReacter()->getReacterable();
            $post = $recipient; // The recipient is the Post that was reserved

            SendReservationCancelledMail::dispatch([
                'reacter_id' => $reacter->id,
                'reacter_type' => get_class($reacter),
                'reacter_email' => $reacter->email,
                'reacter_name' => $reacter->name,
                'reacter_locale' => $reacter->lang_preference ?? config('app.fallback_locale'),
                'post_id' => $post->id,
            ]);
        }
    }
}
