package com.izouma.uwip.web;

import com.izouma.uwip.domain.User;
import com.izouma.uwip.enums.AuthorityName;
import com.izouma.uwip.exception.AuthenticationException;
import com.izouma.uwip.security.JwtTokenUtil;
import com.izouma.uwip.security.JwtUser;
import com.izouma.uwip.security.JwtUserFactory;
import com.izouma.uwip.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil          jwtTokenUtil;
    private final UserService           userService;

    @PostMapping("/login")
    public String loginByUserPwd(String username, String password, Integer expiration) {
        Authentication authentication = authenticate(username, password);
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        return jwtTokenUtil.generateToken(jwtUser);
    }

    @PostMapping("/loginAdmin")
    public String loginByUserPwdAdmin(String username, String password, Integer expiration) {
        Authentication authentication = authenticate(username, password);
        if (!authentication.getAuthorities().contains(new SimpleGrantedAuthority(AuthorityName.ROLE_ADMIN.name()))) {
            throw new AuthenticationException("禁止登录", null);
        }
        JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
        return jwtTokenUtil.generateToken(jwtUser);
    }

    @PostMapping("/phoneLogin")
    @ApiOperation(value = "手机号登录")
    public String phoneLogin(String phone) {
        try {
            User user = userService.loginByPhone(phone);
            return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
        } catch (Exception e) {
            log.error("loginByPhone", e);
            throw new AuthenticationException("登陆错误", e);
        }
    }

    @PostMapping("/mpLogin")
    @ApiOperation(value = "公众号登录")
    public String mpLogin(String code) {
        try {
            User user = userService.loginMp(code);
            return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
        } catch (Exception e) {
            log.error("loginByCode", e);
            throw new AuthenticationException("登陆错误", e);
        }
    }

    @PostMapping("/maLogin")
    @ApiOperation(value = "小程序登录")
    public String maLogin(String code) {
        try {
            User user = userService.loginMa(code);
            return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
        } catch (Exception e) {
            log.error("loginByCode", e);
            throw new AuthenticationException("登陆错误", e);
        }
    }

    /**
     * Authenticates the user. If something is wrong, an {@link AuthenticationException} will be thrown
     *
     * @return Authentication
     */
    private Authentication authenticate(String username, String password) {
        Objects.requireNonNull(username);
        Objects.requireNonNull(password);
        try {
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new AuthenticationException("禁止登录", e);
        } catch (BadCredentialsException e) {
            throw new AuthenticationException("用户名或密码错误", e);
        }
    }
}
