<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\service\sms\SmsService;
use core\base\BaseApiController;

/**
 * @OA\Tag(
 *     name="短信",
 *     description="短信相关接口"
 * )
 */
class SmsController extends BaseApiController
{
    /**
     * @OA\Post(
     *     path="/sms/sendCode",
     *     summary="发送短信验证码",
     *     tags={"短信"},
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             required={"mobile"},
     *             @OA\Property(property="mobile", type="string", description="手机号", example="13800138000"),
     *             @OA\Property(property="scene", type="string", description="模板键名", example="手机号登录=mobile_login,修改密码=reset_password")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功响应",
     *         @OA\JsonContent(
     *             @OA\Property(property="code", type="integer", example=1),
     *             @OA\Property(property="msg", type="string", example="验证码发送成功"),
     *             @OA\Property(property="data", type="object")
     *         )
     *     )
     * )
     */
    public function sendCode()
    {
        $mobile = (string)$this->request->post('mobile', '');
        $scene = (string)$this->request->post('scene', '');

        if ($scene === '') {
            return fail('请选择场景值');
        }

        if ($mobile === '') {
            return fail('手机号不能为空');
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            return fail('手机号格式不正确');
        }

        $code = str_pad((string)mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);

        $smsService = new SmsService();
        $result = $smsService->sendVerifyCode($mobile, $code, $scene);

        if (!$result) {
            return fail($smsService->getError());
        }

        return success('验证码发送成功');
    }
}
