<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Query\SelectQuery;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class AdminUsersTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('admin_users');
        $this->setDisplayField('display_name');
        $this->setPrimaryKey('id');
        $this->addBehavior('Timestamp');

        $this->hasMany('ContactMessages', [
            'foreignKey' => 'reviewed_by_admin_user_id',
        ]);
    }

    public function findActive(SelectQuery $query): SelectQuery
    {
        return $query->where(['AdminUsers.is_active' => true]);
    }

    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmptyString('email');

        $validator
            ->scalar('password_hash')
            ->requirePresence('password_hash', 'create')
            ->notEmptyString('password_hash');

        $validator
            ->scalar('display_name')
            ->maxLength('display_name', 120)
            ->requirePresence('display_name', 'create')
            ->notEmptyString('display_name');

        return $validator;
    }

    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(['email']), ['errorField' => 'email']);

        return $rules;
    }
}
