<?php

namespace App\Jobs;

use App\Mail\ReservationCreatedMail;
use Cog\Contracts\Love\Reaction\Models\Reaction;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendReservationCreatedMail implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $tries = 3;
    public $backoff = [5,30,300]; // wait for 5, 30, or 300 sec before worker tries again
    public $reactionId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($reactionId)
    {
        $this->reactionId = $reactionId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        \Log::info('SendReservationCreatedMail: Starting to process job', ['reaction_id' => $this->reactionId]);

        // Fetch the reaction from the database
        $reaction = \Cog\Laravel\Love\Reaction\Models\Reaction::findOrFail($this->reactionId);
        \Log::info('SendReservationCreatedMail: Reaction loaded', ['reaction_id' => $reaction->getId()]);

        $reacter = $reaction->getReacter()->getReacterable();
        \Log::info('SendReservationCreatedMail: Reacter loaded', [
            'reacter_type' => get_class($reacter),
            'reacter_id' => $reacter->id,
            'reacter_email' => $reacter->email,
        ]);

        // Send the email to the reacter (person making the reservation)
        Mail::to($reacter->email)->send(new ReservationCreatedMail($reaction));

        \Log::info('SendReservationCreatedMail: Email sent successfully', ['to' => $reacter->email]);
    }
}
