<?php

declare(strict_types=1);

namespace App\Http\Controllers\API\V1\Auth;

use Dingo\Api\Http\Response;
use Dingo\Api\Routing\Helpers;
use Illuminate\Support\Carbon;
use Illuminate\Routing\Controller;
use PHPOpenSourceSaver\JWTAuth\JWTGuard;

/**
 * Class RefreshAction
 *
 * @package App\Http\Controllers\API\V1\Auth
 */
class RefreshAction extends Controller
{
    use Helpers;

    /**
     * @return \Dingo\Api\Http\Response
     */
    public function __invoke(): Response
    {
        /** @var JWTGuard $guard */
        $guard = auth('jwt');
        $token = $guard->refresh(false, true);

        return $this->respondWithToken($token);
    }

    /**
     * @param $token
     *
     * @return \Dingo\Api\Http\Response
     */
    protected function respondWithToken($token): Response
    {
        /** @var JWTGuard $guard */
        $guard = auth('jwt');
        $tokenTTL = $guard->factory()->getTTL();
        $tokenExpirationDatetime = Carbon::createFromTimestamp(
            \Carbon\Carbon::now()->unix() + ($tokenTTL * 60)
        );

        $token = [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $tokenTTL * 60,
            'expiration_datetime' => $tokenExpirationDatetime->utc()->toIso8601ZuluString(),
        ];

        return $this->response()->array($token);
    }
}
