<?php

namespace Modules\VrcPortalApi\Entities;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

/**
 * Bearer token for the VRC staff PWA. Authenticates against the existing ERP
 * `users` table — no parallel account store. Only the SHA-256 hash of the token
 * is persisted; the plaintext is returned once to the app.
 */
class VrcStaffToken extends Model
{
    protected $table = 'vrc_staff_tokens';

    protected $fillable = [
        'user_id', 'business_id', 'token_hash', 'user_agent', 'ip', 'expires_at', 'last_used_at',
    ];

    protected $casts = [
        'expires_at'   => 'datetime',
        'last_used_at' => 'datetime',
    ];

    public static function issue(User $user, ?string $userAgent, ?string $ip): string
    {
        $ttlDays = (int) config('vrcportalapi.staff_token_ttl_days', 30);
        $plain = 'vstf-' . Str::random(40);

        self::create([
            'user_id'    => $user->id,
            'business_id' => $user->business_id,
            'token_hash' => hash('sha256', $plain),
            'user_agent' => $userAgent ? substr($userAgent, 0, 255) : null,
            'ip'         => $ip,
            'expires_at' => $ttlDays ? now()->addDays($ttlDays) : null,
        ]);

        return $plain;
    }

    public static function lookup(string $plain): ?User
    {
        if ($plain === '') {
            return null;
        }
        $row = self::where('token_hash', hash('sha256', $plain))->first();
        if (! $row) {
            return null;
        }
        if ($row->expires_at && $row->expires_at->isPast()) {
            return null;
        }
        $row->forceFill(['last_used_at' => now()])->save();

        return User::find($row->user_id);
    }

    public static function revoke(string $plain): void
    {
        self::where('token_hash', hash('sha256', $plain))->delete();
    }
}
