package com.sonic.frog.controller.web;

import com.sonic.bear.lib.client.UserLoginClient;
import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.common.utils.IpAddressUtils;
import com.sonic.frog.domain.input.ThirdLoginOrRegisterInput;
import com.sonic.frog.domain.output.ThirdLoginOrRegisterOutput;
import com.sonic.frog.limit.RequestLimit;
import com.sonic.frog.service.ThirdLoginOrRegisterService;
import com.sonic.frog.utils.HttpHeaderUtils;
import com.sonic.sdk.api.annotation.IgnoreAuth;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Web-三方账号
 * @author code
 */
@RestController
@Slf4j
public class LoginWeb {

    @Autowired
    private ThirdLoginOrRegisterService thirdLoginOrRegisterService;
    @Autowired
    private UserLoginClient userLoginClient;

    @IgnoreAuth
    @RequestLimit(count=50, time=300000, message = "operate too frequently，please try again 5min later (101) ")
    @ApiOperation(value = "三方账号注册登录", tags = {"Web-三方账号"})
    @PostMapping("/web/third/login")
    public Result<ThirdLoginOrRegisterOutput> loginOrRegister(@Valid @RequestBody ThirdLoginOrRegisterInput input, @ApiParam(hidden = true) HttpServletRequest request) {
        input.setIp(IpAddressUtils.getIpAddress(request));
        input.setUserAgent(HttpHeaderUtils.getUserAgent(request));
        //验证用户的账号是要进行密码登录还是注册
        ThirdLoginOrRegisterOutput output = thirdLoginOrRegisterService.loginOrRegister(input);
        return Result.success(output);
    }


    @ApiOperation(value = "退出登录", tags = {"Web-三方账号"})
    @PostMapping("/web/user/logout")
    public Result<Void> logout(@ApiParam(hidden = true) Session session) {
        userLoginClient.logout(session.getToken());
        return Result.success();
    }

}
