<?php

namespace App\Services\Api;

use App\Models\TokenValidation;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ApiTokenService
{
    public function issue(string $username, string $password): ?array
    {
        $account = TokenValidation::where('username', $username)->first();

        if (! $account || ! Hash::check($password, $account->password)) {
            return null;
        }

        $plainToken = Str::random(80);
        $expiresAt = Carbon::now()->addDay();

        $account->forceFill([
            'token' => hash('sha256', $plainToken),
            'expires_at' => $expiresAt,
        ])->saveOrFail();

        return [
            'token_type' => 'Bearer',
            'access_token' => $plainToken,
            'expires_at' => $expiresAt->toDateTimeString(),
        ];
    }

    public function isValid(Request $request): bool
    {
        $rawToken = trim(str_replace('Bearer ', '', (string) $request->header('Authorization')));

        if ($rawToken === '') {
            return false;
        }

        $hashedToken = hash('sha256', $rawToken);

        $token = TokenValidation::where('token', $hashedToken)
            ->orWhere('token', $rawToken)
            ->first();

        return $token && Carbon::parse($token->expires_at)->isFuture();
    }
}
