<?php

namespace App\Jobs;

use App\Mail\ProfileLinkChangedMail;
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\Log;
use Illuminate\Support\Facades\Mail;

class SendProfileLinkChangedMail 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

    protected $recipient;
    protected $linkedProfile;
    protected $action;

    /**
     * Create a new job instance.
     *
     * @param mixed $recipient The profile receiving the notification
     * @param mixed $linkedProfile The profile that was attached/detached
     * @param string $action Either 'attached' or 'detached'
     * @return void
     */
    public function __construct($recipient, $linkedProfile, $action = 'attached')
    {
        $this->recipient = $recipient;
        $this->linkedProfile = $linkedProfile;
        $this->action = $action;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info('SendProfileLinkChangedMail: Job starting', [
            'recipient_id' => $this->recipient->id,
            'recipient_type' => get_class($this->recipient),
            'recipient_email' => $this->recipient->email ?? 'NO EMAIL',
            'linked_profile_id' => $this->linkedProfile->id,
            'linked_profile_type' => get_class($this->linkedProfile),
            'action' => $this->action,
        ]);

        // Check if recipient has an email
        if (empty($this->recipient->email)) {
            Log::warning('SendProfileLinkChangedMail: Recipient has no email address', [
                'recipient_id' => $this->recipient->id,
                'recipient_type' => get_class($this->recipient),
            ]);
            return;
        }

        try {
            // Send the email to the recipient
            Mail::to($this->recipient->email)->send(
                new ProfileLinkChangedMail($this->recipient, $this->linkedProfile, $this->action)
            );

            Log::info('SendProfileLinkChangedMail: Email sent successfully', [
                'recipient_email' => $this->recipient->email,
                'action' => $this->action,
            ]);
        } catch (\Exception $e) {
            Log::error('SendProfileLinkChangedMail: Failed to send email', [
                'recipient_email' => $this->recipient->email ?? 'NO EMAIL',
                'action' => $this->action,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            throw $e;
        }
    }
}
