<?php

namespace App\Services;

use App\Models\DeviceToken;
use App\Models\User;
use Illuminate\Support\Str;

/**
 * Issues and resolves the "trusted device" token behind Quick PIN login.
 *
 * The raw token is a 64-char random string, shown to the client exactly once
 * (mirroring Sanctum's personal-access-token pattern). Only its SHA-256
 * digest is persisted — a deterministic, queryable hash, unlike bcrypt.
 */
class DeviceTokenService
{
    public const EXPIRY_DAYS = 60;

    public function issue(User $user): string
    {
        $raw = Str::random(64);

        DeviceToken::create([
            'user_id' => $user->getKey(),
            'token_hash' => hash('sha256', $raw),
            'expires_at' => now()->addDays(self::EXPIRY_DAYS),
        ]);

        return $raw;
    }

    public function resolve(string $rawToken): ?User
    {
        $deviceToken = DeviceToken::query()
            ->where('token_hash', hash('sha256', $rawToken))
            ->first();

        if ($deviceToken === null || $deviceToken->expires_at->isPast()) {
            return null;
        }

        return $deviceToken->user;
    }
}
