<?php

namespace AuthStack\Driver\AUDGeneric\App\Services;

use DB;
use Carbon\Carbon;
use AuthStack\Driver\AUDGeneric\Driver;
use AuthStack\Driver\Errors\NoAuthSourceError;
use AuthStack\Driver\AUDGeneric\App\Requests\PasswordReset;
use AuthStack\Driver\AUDGeneric\App\Requests\PasswordResetWithToken;

class Token
{
    /**
     * @param PasswordResetWithToken $request
     * @return bool
     * @throws NoAuthSourceError
     */
    public static function validateToken(PasswordResetWithToken $request)
    {
        $connId = (new Driver())->getAuthSourceId();

        $validate = DB::table('password_resets')
            ->where('email', $request->getEmail())
            ->where('token', $request->getToken())
            ->where('driver_id', $connId)
            ->where('active', true)
            ->whereRAW('UNIX_TIMESTAMP(expires_at) > ?', [Carbon::now()->timestamp])
            ->first();

        $validate = (array)$validate;

        return count($validate) > 0 ? true : false;
    }

    /**
     * @param PasswordReset $request
     * @param $email
     * @param int|null $connId
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder|object|null
     */
    public static function tokenHandler(PasswordReset $request, $email, ?int $connId)
    {
        //Create Password Reset Token
        $token = DB::table('password_resets')->insertGetId([
            'email' => $email,
            'token' => str_random(60),
            'username' => $request->getUsername(),
            'active' => true,
            'driver_id' => $connId,
            'created_at' => Carbon::now(),
            'expires_at' => Carbon::now()->addDay(1),
        ]);

        //Get the token just created above
        $tokenData = DB::table('password_resets')
            ->where('id', $token)
            ->first();

        $oldTokens = DB::table('password_resets')
            ->where('email', $email)
            ->where('active', true)
            ->where('driver_id', $connId)
            ->whereNotIn('id', [$tokenData->id])
            ->pluck('id')
            ->toArray();

        //Disable old tokens
        DB::table('password_resets')
            ->whereIn('id', $oldTokens)
            ->update(['active' => 0]);

        return $tokenData;
    }
}