<?php

namespace Modules\WebPilotAI\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Modules\WebPilotAI\Events\WebsiteGenerationFailed;
use Modules\WebPilotAI\Mail\WebsiteGenerationHasFailed;

class SendWebsiteGenerationFailureNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(WebsiteGenerationFailed $event): void
    {
        $website = $event->website; // ->loadMissing('user'); // Optionally ensure user is loaded here too

        if (!$website->user) {
            Log::warning("Could not send WebsiteGenerationFailed email: User relationship not loaded or null for website ID: {$website->id}. Error: {$event->errorMessage}");
            return;
        }
        if (!$website->user->email) {
            Log::warning("Could not send WebsiteGenerationFailed email: User email missing for user ID: {$website->user->id}, website ID: {$website->id}. Error: {$event->errorMessage}");
            return;
        } else {
            Mail::to($website->user->email)
                ->send(new WebsiteGenerationHasFailed($website, $event->errorMessage));
            Log::info("Sent WebsiteGenerationFailed email to {$website->user->email} for website ID: {$website->id}. Original error: {$event->errorMessage}");
        }
    }
}