<?php

declare(strict_types=1);

namespace app\api\validate;

use think\Validate;

class User extends Validate
{
    protected $failException = true;

    protected $rule = [
        'username'     => 'require|regex:^[a-zA-Z][a-zA-Z0-9_]{2,15}$|unique:user',
        'password'     => 'require|regex:^(?!.*[&<>"\'\n\r]).{6,32}$',
        'registerType' => 'require|in:email,mobile',
        'email'        => 'email|unique:user|requireIf:registerType,email',
        'mobile'       => 'mobile|unique:user|requireIf:registerType,mobile',
        'captcha'      => 'require',
        'captchaId'    => 'require',
        'captchaInfo'  => 'require',
    ];

    protected $scene = [
        'register' => ['username', 'password', 'registerType', 'email', 'mobile', 'captcha'],
    ];

    public function sceneLogin(): static
    {
        $fields = ['username', 'password'];

        $userLoginCaptchaSwitch = config('buildadmin.user_login_captcha');
        if ($userLoginCaptchaSwitch) {
            $fields[] = 'captchaId';
            $fields[] = 'captchaInfo';
        }

        return $this->only($fields)->remove('username', ['regex', 'unique']);
    }

    public function __construct()
    {
        $this->field = [
            'username'     => __('Username'),
            'email'        => __('Email'),
            'mobile'       => __('Mobile'),
            'password'     => __('Password'),
            'captcha'      => __('captcha'),
            'captchaId'    => __('captchaId'),
            'captchaInfo'  => __('captcha'),
            'registerType' => __('Register type'),
        ];
        $this->message = array_merge($this->message, [
            'username.regex' => __('Please input correct username'),
            'password.regex' => __('Please input correct password')
        ]);
        parent::__construct();
    }
}
