<?php

namespace App\Jobs;

use App\Mail\ProfileEditedByAdminMail;
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 SendProfileEditedByAdminMail implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    protected $profile;
    protected $changedFields;

    /**
     * Create a new job instance.
     *
     * @param mixed $profile The profile that was edited
     * @param array $changedFields Array of field names that were changed
     * @return void
     */
    public function __construct($profile, $changedFields = [])
    {
        $this->profile = $profile;
        $this->changedFields = $changedFields;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (!$this->profile->email) {
            Log::warning('SendProfileEditedByAdminMail: Profile has no email address', [
                'profile_id' => $this->profile->id,
                'profile_type' => get_class($this->profile),
            ]);
            return;
        }

        Log::info('SendProfileEditedByAdminMail: Sending email', [
            'profile_id' => $this->profile->id,
            'profile_type' => get_class($this->profile),
            'profile_email' => $this->profile->email,
            'changed_fields' => $this->changedFields,
        ]);

        Mail::to($this->profile->email)->send(
            new ProfileEditedByAdminMail($this->profile, $this->changedFields)
        );

        Log::info('SendProfileEditedByAdminMail: Email sent successfully');
    }
}
