<?php

namespace Modules\Base\Http\Requests;

use Modules\Base\Services\Exception\PhoneNullException;
use Modules\Base\Services\SmsService;

class SmsRequest extends BaseRequest
{
    /**
     * @throws \Throwable
     *
     * @return array
     */
    public function rules()
    {
        $types = SmsService::getTypes();

        $guard = $this->isApi() ? 'api' : null;
        if (SmsService::needAuth($this->type)) {
            abort_if(auth($guard)->guest(), 401, '需要登陆');
            $user = auth($guard)->user();

            if (SmsService::needUserPhone($this->type)) {
                $phone = $user->phone;
                throw_unless($phone, new PhoneNullException());
                $this->request->add(['phone' => $phone]);
            }
        }

        $rules = [
            'type' => 'required|in:'.implode(',', $types),
            'captcha_key' => 'required|string',
            'captcha_code' => 'bail|required|captcha_api:'.$this->captcha_key,
            //'phone' => 'bail|required|regex:/^1[345789][0-9]{9}$/',
        ];

        if (!SmsService::needUserPhone($this->type)) {
            $rules['phone'] = 'bail|required|regex:/^1[345789][0-9]{9}$/'.SmsService::appendPhoneValidateRule($this->type);
        }

        return $rules;
    }

    public function attributes()
    {
        return [
            'captcha_key' => '图片验证码 key',
            'captcha_code' => '图片验证码',
            'phone' => '手机号',
        ];
    }

    public function messages()
    {
        return [
            'captcha_code.captcha_api' => '图片验证码错误或已过期',
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}
