<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

use App\Mail\PasswordReset;
use App\Mail\UserInvitation;

use App\Models\User;

class SendAuthEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $destination, $type, $token;

    public function __construct($_type, $_destination, $_token)
    {
        $this->type = $_type;
        $this->destination = env('APP_ENV') === 'development' ? config('security.development_email_direct') : $_destination;
        $this->token = $_token;
    }

    public function handle()
    {
        $to_send = null;
        $col_to_check = null;

        switch($this->type) {
            case 'setup':
                $col_to_check = 'signup_token';
                $to_send = new UserInvitation($this->token);
                break;
            case 'reset':
                $col_to_check = 'reset_token';
                $to_send = new PasswordReset($this->token);
                break;
        }

        // Always check whether the token is valid before doing anything, and that the user has not since been deleted.
        if($to_send !== null && $col_to_check !== null && User::where($col_to_check, '=', $this->token)->count() != 0) {
            Mail::to($this->destination)->send($to_send);
        }
    }
}
