<?php

namespace App\Listeners;

use App\Jobs\SendReactionCreatedMail;
use App\Jobs\SendReservationCreatedMail;
use App\Models\MessageSetting;
use Cog\Laravel\Love\Reaction\Events\ReactionHasBeenAdded;
use Illuminate\Support\Facades\Log;

class ReactionCreatedListener
{
    public function handle(ReactionHasBeenAdded $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();

        $sendReactionEmail = false;

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

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

        if ($sendReactionEmail) {
            // Dispatch appropriate job based on reaction type
            if ($reactionType === 'Reserve') {
                SendReservationCreatedMail::dispatch($reaction->getId());
            } else {
                SendReactionCreatedMail::dispatch($reaction);
            }
        }
    }
}
