<?php

namespace App\Jobs;

use App\Models\OrderProduct;
use App\Mail\ProductOrderUserMail;
use App\Mail\ProductOrderAdminMail;
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 ProcessProductOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public OrderProduct $order;

    /**
     * Create a new job instance.
     */
    public function __construct(OrderProduct $order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        // 🔐 Reload & ensure idempotency
        $order = OrderProduct::with(['user', 'product'])
            ->where('id', $this->order->id)
            ->where('status', 'completed')
            ->where('is_paid', true)
            ->first();

        if (! $order) {
            return;
        }

        // 📧 Send user email
        Mail::to($order->user->email)
            ->send(new ProductOrderUserMail($order));

        // 📧 Send admin email
        Mail::to(env('ADMIN_EMAIL'))
            ->queue(new ProductOrderAdminMail($order));
        }
}
