<?php

namespace Modules\PortalApi\Entities;

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

class PortalOtpChallenge extends Model
{
    protected $table = 'portal_otp_challenges';

    public $incrementing = false;
    protected $keyType   = 'string';

    protected $fillable = [
        'id', 'owner_id', 'phone', 'code_hash',
        'attempts', 'expires_at', 'used_at',
    ];

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

    public const MAX_ATTEMPTS = 5;
    public const TTL_MINUTES  = 10;

    public static function open(string $phone, ?int $ownerId, string $codeHash): self
    {
        return self::create([
            'id'         => (string) Str::uuid(),
            'owner_id'   => $ownerId,
            'phone'      => $phone,
            'code_hash'  => $codeHash,
            'attempts'   => 0,
            'expires_at' => now()->addMinutes(self::TTL_MINUTES),
        ]);
    }

    public function isFresh(): bool
    {
        return ! $this->used_at
            && $this->attempts < self::MAX_ATTEMPTS
            && $this->expires_at?->isFuture();
    }
}
