package com.sonic.bear.controller.api;

import com.sonic.bear.domain.input.KickOutInput;
import com.sonic.bear.domain.input.LogoutInput;
import com.sonic.bear.domain.input.ThirdUserLoginInput;
import com.sonic.bear.service.UserService;
import com.sonic.bear.service.UserSessionService;
import com.sonic.common.auth.domains.Session;
import com.sonic.common.rpc.Result;
import com.sonic.sdk.api.annotation.InternalRpc;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * API-账号登录管理
 * @author coder
 */
@InternalRpc(path = "/api/**")
@Validated
@RestController
public class UserLoginApi {

    @Autowired
    private UserService userService;
    @Autowired
    private UserSessionService userSessionService;

    @ApiOperation(value = "三方账号登录", tags = {"API-账号登录"})
    @PostMapping("/api/auth/third-user-login")
    public Result<Session> thirdUserLogin(@RequestBody @Valid ThirdUserLoginInput input) {
        //执行账号验证操作
        Long userId = userService.thirdLoginOrRegister(input.getThirdType(), input.getOpenId(), input.getEmail(), input.getNickname());
        //执行登录操作
        UserSessionService.CreateSessionReq req = UserSessionService.CreateSessionReq.builder()
                .userId(userId)
                .clientCode(input.getClientCode())
                .loginType(input.getThirdType().name())
                .deviceId(input.getDeviceId())
                .ip(input.getIp())
                .userAgent(input.getUserAgent())
                .build();
        Session session = userSessionService.createSession(req);
        return Result.success(session);
    }

    @ApiOperation(value = "退出登录", tags = {"API-账号登录"})
    @PostMapping("/api/auth/logout")
    public Result<Void> logout(@RequestBody @Valid LogoutInput input) {
        userSessionService.logout(input);
        return Result.success();
    }

    @ApiOperation(value = "踢下线", tags = {"API-账号登录"})
    @PostMapping("/api/auth/kick-out")
    public Result<Void> kickOut(@RequestBody @Valid KickOutInput input) {
        userSessionService.kickOut(input);
        return Result.success();
    }

}
