<?php

namespace App\Services\Auth;

use App\Models\Auth\MobileAccessToken;
use App\Models\Datmas\Siswa;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

class MobileTokenService
{
    public function issueToken(Siswa $siswa, string $nouid, string $deviceName, ?string $ipAddress = null, ?string $userAgent = null): array
    {
        $plainTextToken = Str::random(64);

        MobileAccessToken::query()
            ->where('nouid', $nouid)
            ->where('name', $deviceName)
            ->delete();

        $token = MobileAccessToken::create([
            'nouid' => $nouid,
            'name' => $deviceName,
            'token_hash' => hash('sha256', $plainTextToken),
            'ip_address' => $ipAddress,
            'user_agent' => $userAgent,
            'last_used_at' => now(),
            'expires_at' => now()->addDays(30),
        ]);

        return [$token, $plainTextToken];
    }

    public function findValidToken(string $plainTextToken): ?MobileAccessToken
    {
        $token = MobileAccessToken::query()
            ->where('token_hash', hash('sha256', $plainTextToken))
            ->first();

        if (!$token) {
            return null;
        }

        if ($token->isExpired()) {
            $token->delete();

            return null;
        }

        return $token;
    }

    public function touch(MobileAccessToken $token): void
    {
        $token->forceFill([
            'last_used_at' => Carbon::now(),
        ])->save();
    }
}
