<?php

namespace App\Jobs;

use App\Mail\GiftVoucherIssued;
use App\Models\GiftVoucher;
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 NotifyGiftVoucherReminder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public GiftVoucher $voucher, public bool $expiry = false) {}

    public function handle(): void
    {
        $voucher = $this->voucher->fresh();

        if (! $voucher || $voucher->isRedeemed() || $voucher->isRefunded() || $voucher->isExpired()) {
            return;
        }

        $recipients = collect([$voucher->purchaser_email, $voucher->recipient_email])
            ->filter()
            ->unique()
            ->all();

        foreach ($recipients as $email) {
            Mail::to($email)->queue((new GiftVoucherIssued($voucher, $email === $voucher->recipient_email))->with([
                'isReminder' => true,
                'isExpiry' => $this->expiry,
            ]));
        }
    }
}
