<?php

namespace Modules\User\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Hash;
use Modules\User\Events\Login;
use Modules\User\Models\User;

class AuthController extends Controller
{
    use ValidatesRequests;
    /**
     * @param Request $request
     * @return array
     */
    public function login(Request $request): array
    {
        /* @var User $user */
        $user = User::query()->where('email', $request->get('email'))->first();

        Event::dispatch(new Login($request, $user));
        if ($user && $user->status != 1){
            throw new FailedException('账号不存在或已停用！');
        }
        if ($user && Hash::check($request->get('password'), $user->password)) {
            $token = $user->createToken('token')->plainTextToken;
            return compact('token');
        }

        throw new FailedException('登录失败！请检查邮箱或者密码');
    }


    /**
     * logout
     *
     * @return array
     */
    public function logout(): array
    {
        /* @var  User $user */
        $user = Auth::guard(getGuardName())->user();

        $user->currentAccessToken()->delete();

        return [];
    }

    /***
     *  发送邮件验证码
     * name: sendCode
     * date 2023/04/14 14:41
     */
    public function sendCode(Request $request)
    {
        $email = $request->input('email', "");
        if (empty($email)) {
            throw new FailedException('请输入邮箱！');
        }

        $user = User::query()->where('email', $email)->first();
        if(empty($user)){
            throw new FailedException('正确请输入邮箱！');
        }
        $code = random(6, true);
        cache([$email => $code], 120);
        $param = [
            'subject' => "重置密码验证",
            'body' => "验证码为：{$code}，您正在进行登录密码重置，验证码2分钟内有效，泄露验证码会影响您的账号安全，如果不是本次操作请忽略本次邮件！"
        ];

        sendEmail( [[ 'address' =>$email, 'name' => $user->username]],$param);

        return  response()->json(['code' => 10000, "message" => "发送成功",'data' => []]);
    }

    /**
     *  重置密码
     */
    public function reSetPassword(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
            'code' => 'required',
            'password' => 'required|string|min:6',
            'password_confirmation' => 'required|string|same:password'
        ],['email' =>  "邮箱不能为空",'code' =>  "验证码不能为空",'password'=>"密码不能为空",'password_confirmation'  =>  "两次输入密码不一致"]);

        $email = $request->input('email', "");
        $code =  $request->input('code', "");
        $password = $request->input('password');

        if(cache($email) != $code){
            throw new FailedException('验证码不正确或已过期！');
        }
        $user = User::query()->where('email', $email)->first();
        if(empty($user)){
            throw new FailedException('正确请输入邮箱！');
        }

        $password = bcrypt($password);
        $res =  User::query()->where('id',$user->id)->update(['password' => $password]);
        return response()->json(['code' => 10000, "message" => "操作成功",'data' => []]);
    }
}
