package com.example.sjkbf.controller;

import com.example.sjkbf.entity.CommonResult;
import com.example.sjkbf.entity.DTO.LoginRequest;
import com.example.sjkbf.entity.DTO.LoginResponse;
import com.example.sjkbf.service.UserService;
import com.example.sjkbf.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginRequest request) {
        // 1. 创建认证令牌（未认证状态）
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());

        // 2. 执行认证（Spring Security 自动调用 UserDetailsService）
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        // 3. 认证成功，生成 JWT
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetails);

        // 4. 提取权限信息
        List<String> roles = userDetails.getAuthorities().stream()

                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        // 5. 返回响应
        return ResponseEntity.ok(
                new LoginResponse("Bearer "+token, userDetails.getUsername(), roles)
        );
    }

    // 用户注册接口
    @PostMapping("/register")
    public ResponseEntity<CommonResult<String>> register(@Valid @RequestBody LoginRequest request) {
        if (request.getUsername()==null|| request.getUsername().isEmpty()) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.failed(201,"用户名为空"));
        }
        if (request.getPassword()==null|| request.getPassword().isEmpty()) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.failed(201,"密码为空"));
        }
        if (request.getQq()==null|| request.getQq().isEmpty()) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.failed(201,"安全口令为空"));
        }

        // 检查用户名是否已存在
        if (userService.isUsernameExist(request.getUsername())) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.failed(201,"用户名已存在"));
        }


        // 保存用户
        userService.registerUser(request);
        return ResponseEntity.ok(CommonResult.success("注册成功"));
    }

    //找回密码
    @PostMapping("/changePassword")
    public ResponseEntity<CommonResult<String>> changePassword(@Valid @RequestBody LoginRequest request) {
        if (request.getUsername()==null|| request.getUsername().isEmpty()) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.failed(201,"用户名为空"));
        }
        if (request.getPassword()==null|| request.getPassword().isEmpty()) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.failed(201,"密码为空"));
        }
        if (request.getQq()==null|| request.getQq().isEmpty()) {
            return ResponseEntity.status(HttpStatus.CREATED).body(CommonResult.failed(201,"安全口令为空"));
        }

        // 保存用户
        userService.updatePassword(request);
        return ResponseEntity.ok(CommonResult.success("修改成功"));
    }

}