<?php

declare(strict_types=1);

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

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

/**
 * Class RefreshAction
 */
class RefreshAction extends Controller
{
    use Helpers;

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

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

    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);
    }
}
