<?php

namespace App\Jobs;

use Mtc\MercuryDataModels\Enums\VehicleSubscriptionEventType;
use App\Mail\VehicleSubscriptionNotificationMail;
use Carbon\Carbon;
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;
use Mtc\MercuryDataModels\VehicleSubscription;

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

    public function __construct(
        private readonly VehicleSubscription $subscription,
        private readonly VehicleSubscriptionEventType $eventType,
        private readonly array $eventData = []
    ) {
        $this->onQueue('emails');
    }

    public function handle(): void
    {
        // Rate limiting: Don't send more than one notification per event type per 24 hours
        if ($this->wasRecentlyNotified()) {
            Log::info('Vehicle subscription notification skipped due to rate limiting', [
                'subscription_id' => $this->subscription->id,
                'event_type' => $this->eventType->value,
            ]);
            return;
        }

        // Ensure vehicle is still available (not sold/archived)
        $vehicle = $this->subscription->vehicle;
        if (!$vehicle || $vehicle->is_sold || $vehicle->deleted_at) {
            Log::info('Vehicle subscription notification skipped - vehicle no longer available', [
                'subscription_id' => $this->subscription->id,
                'vehicle_id' => $this->subscription->vehicle_id,
            ]);
            return;
        }

        // Validate customer email
        $customer = $this->subscription->customer;
        if (!$customer || !filter_var($customer->email, FILTER_VALIDATE_EMAIL)) {
            Log::warning('Vehicle subscription notification skipped - invalid customer email', [
                'subscription_id' => $this->subscription->id,
                'customer_id' => $this->subscription->customer_id,
            ]);
            return;
        }

        try {
            Mail::to($customer->email)->send(
                new VehicleSubscriptionNotificationMail(
                    $this->subscription,
                    $this->eventType,
                    $this->eventData
                )
            );

            // Update last notified timestamp
            $this->subscription->update(['last_notified_at' => Carbon::now()]);

            Log::info('Vehicle subscription notification sent', [
                'subscription_id' => $this->subscription->id,
                'event_type' => $this->eventType->value,
                'customer_email' => $customer->email,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send vehicle subscription notification', [
                'subscription_id' => $this->subscription->id,
                'event_type' => $this->eventType->value,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    private function wasRecentlyNotified(): bool
    {
        if (!$this->subscription->last_notified_at) {
            return false;
        }

        return $this->subscription->last_notified_at->greaterThan(Carbon::now()->subHours(24));
    }
}
