<?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 Cake\Chronos\Traits\TimezoneTrait;
use PHPOpenSourceSaver\JWTAuth\JWTGuard;

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

    /**
     * @return \Dingo\Api\Http\Response
     */
    public function __invoke(): Response
    {
        /** @var JWTGuard $guard */
        $guard = auth('jwt');
        /** @var \App\Models\Pouzivatel\Pouzivatel $pouzivatel */
        $pouzivatel = auth()->user();

        if (! $token = $guard->login($pouzivatel)) {
            $this->response()->errorUnauthorized();
        }

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

    /**
     * @param $token
     *
     * @return \Dingo\Api\Http\Response
     */
    protected function respondWithToken($token): Response
    {
        /** @var JWTGuard $guard */
        $guard = auth('jwt');
        $tokenExpirationDatetime = Carbon::createFromTimestamp($guard->getClaim('exp'));

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

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