<?php

namespace App\Listeners;

use App\Models\User;
use Illuminate\Auth\Events\Login;

class IssueApiToken
{
    public function handle(Login $event): void
    {
        /** @var User $user */
        $user = $event->user;

        $this->createToken($user);
    }

    public function createToken(User $user): void
    {
        // Delete only this session's existing token (if any)
        if ($tokenId = session('api_token_id')) {
            $user->tokens()->where('id', $tokenId)->delete();
        }

        $newToken = $user->createToken(
            'frontend',
            ['*'],
            now()->addHours(4)
        );

        session([
            'api_token'    => $newToken->plainTextToken,
            'api_token_id' => $newToken->accessToken->id,
        ]);
    }
}
