<?php

namespace AuthStack\UserDirectory\Model;

use AuthStack\UserDirectory\Exceptions\AccountException;
use Illuminate\Database\Eloquent\Model;

class Policy extends Model
{
    protected $table = 'policies';
    public $timestamps = true;

    /**
     * @param Account $account
     * @return bool
     */
    public function isPasswordOutdated(Account $account): bool
    {
        // No max age - not outdated
        if(!$this->hasMaxAge())
        {
            return false;
        }

        // Check the max age and compare it to number of days since last password change
        return $this->getMaxAge() >= $account->getDaysSinceLastPasswordChange();
    }

    /**
     * @param int $current
     * @return bool
     */
    public function exceedsNumberOfAttempts(int $current): bool
    {
        if(!$this->hasLockout()) return false;

        return $current >= $this->getLockout();
    }

    /**
     * @param \DateTime $locked_at
     * @return bool
     */
    public function lockoutExpired(\DateTime $locked_at): bool
    {
        if(!$this->hasLockout()) return true;

        $days = (now()->diff($locked_at, true))->format('%a');

        return $days >= $this->getLockout();
    }

    /**
     * @return bool
     */
    public function hasLockout(): bool
    {
        return -1 !== $this->getLockout();
    }

    /**
     * @return int
     */
    public function getLockout(): int
    {
        if(empty($this->lockout)) return -1;

        return (int)$this->lockout;
    }

    /**
     * @return bool
     */
    public function hasMaxAge(): bool
    {
        return !is_null($this->max_age);
    }

    /**
     * @return int
     */
    public function getMaxAge(): int
    {
        return (int)$this->max_age;
    }
}