<?php

namespace Modules\PortalApi\Entities;

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

class PortalMagicToken extends Model
{
    protected $table = 'portal_magic_tokens';

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

    protected $hidden = ['token_hash'];

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

    public const TTL_MINUTES = 15;

    /** Issue + return the plaintext token to embed in the email link. */
    public static function issue(PortalOwner $owner, string $email, ?string $ua, ?string $ip): string
    {
        $plain = Str::random(48);
        self::create([
            'owner_id'   => $owner->id,
            'email'      => $email,
            'token_hash' => hash('sha256', $plain),
            'expires_at' => now()->addMinutes(self::TTL_MINUTES),
            'user_agent' => $ua,
            'ip'         => $ip,
        ]);
        return $plain;
    }

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