<?php

namespace App\Jobs\Vrm;

use App\Mail\SendEmail;
use App\Services\Trading\TradingSettingsService;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
use Throwable;

class SendMail implements ShouldQueue
{
    use Dispatchable;
    use Queueable;

    protected string $email;

    /** @var array<string, mixed> */
    protected array $details;

    protected string $subject;

    protected ?string $replyTo;

    /** @var array<int, string> */
    protected array $ccRecipients;

    /** @var array<int, string> */
    protected array $bccRecipients;

    /** @var array<int, array<string, mixed>> */
    protected array $attachments;

    protected ?Mailable $mailable;

    protected ?string $notificationType;

    /**
     * Create a new job instance.
     */
    public function __construct(
        string $email,
        array $details = [],
        string $subject = 'NEW MAIL ALERT!',
        ?Mailable $mailable = null,
        ?string $replyto = null,
        array $ccrecipients = [],
        array $bccrecipients = [],
        array $attachment = [],
        ?string $notificationType = null
    ) {
        $this->email = $email;
        $this->details = $details;
        $this->subject = $subject;
        $this->mailable = $mailable;
        $this->replyTo = $replyto;
        $this->ccRecipients = $ccrecipients;
        $this->bccRecipients = $bccrecipients;
        $this->attachments = $attachment;
        $this->notificationType = $notificationType;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if (! $this->emailNotificationsEnabled()) {
            return;
        }

        if ($this->mailable instanceof Mailable) {
            Mail::to($this->email)->sendNow($this->mailable);

            return;
        }

        Mail::to($this->email)->sendNow(new SendEmail(
            _details: $this->details,
            _subject: $this->subject,
            _replyToEmail: $this->replyTo,
            _ccRecipients: $this->ccRecipients,
            _bccRecipients: $this->bccRecipients,
            _attachments: $this->attachments
        ));
    }

    protected function emailNotificationsEnabled(): bool
    {
        try {
            $settings = app(TradingSettingsService::class);
            if ($this->notificationType !== null) {
                return $settings->isEmailTypeEnabled($this->notificationType);
            }

            return $settings->emailNotificationsEnabled();
        } catch (Throwable) {
            return true;
        }
    }
}
