<?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\CodeUserReset;
use App\Models\User;
use Carbon\Carbon;

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

    protected $destination, $type, $token;

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

    public function handle()
    {
        $to_send = null;
        
        $valid = false;

        switch($this->type) {
            case 'setup':
                $valid = User::where('signup_token', '=', $this->token)->count() != 0;

                $to_send = new UserInvitation($this->token);
                break;
            case 'reset':
                $valid = CodeUserReset::where([
                    ['token', '=', hash('sha256', $this->token)],
                    ['expiry_at', '>', Carbon::now()]
                ])->count();

                $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 && $valid) {
            Mail::to($this->destination)->send($to_send);
        }
    }
}
