<?php

namespace Modules\PortalApi\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class PortalOwnerToken extends Model
{
    protected $table = 'portal_owner_tokens';

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

    protected $hidden = ['token_hash'];

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

    public function owner(): BelongsTo
    {
        return $this->belongsTo(PortalOwner::class, 'owner_id');
    }

    /**
     * Issue a fresh token for an owner. Returns the PLAINTEXT token to hand
     * to the PWA; only its sha256 hash is persisted.
     */
    public static function issue(PortalOwner $owner, ?string $userAgent, ?string $ip, ?int $ttlDays = 90): string
    {
        $plain = 'owner-' . Str::random(40);
        self::create([
            'owner_id'   => $owner->id,
            'token_hash' => hash('sha256', $plain),
            'user_agent' => $userAgent,
            'ip'         => $ip,
            'expires_at' => $ttlDays ? now()->addDays($ttlDays) : null,
        ]);
        return $plain;
    }

    /** Resolve a bearer token back to its owner, touching last_used_at. */
    public static function lookup(string $plain): ?PortalOwner
    {
        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 $row->owner;
    }
}
