package org.cmh.backend.authentication.controller;


import org.cmh.backend.Utils.JwtUtil;
import org.cmh.backend.Utils.JwtVerify;
import org.cmh.backend.authentication.dto.*;
import org.cmh.backend.authentication.model.UserHS;
import org.cmh.backend.authentication.service.UserService;
import org.cmh.backend.authentication.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
class AuthenticationController {

    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @GetMapping("/hello")
    public String hello() {
        return "Hello SpringBoot!";
    }


    @PostMapping("/register")
    public ResponseEntity<RegisterResponse> register(@RequestBody RegisterRequest request) {
        try {
            boolean isRegistered = userService.registerUser(request);
            if (isRegistered) {
                return new ResponseEntity<>(new RegisterResponse("注册成功"), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(new RegisterResponse("注册失败:用户已存在"), HttpStatus.BAD_REQUEST);
            }
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(new RegisterResponse("注册失败:输入格式有误"), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(new RegisterResponse("注册失败:服务器错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        boolean isValidUser = userService.loginUser(loginRequest.getUsername(), loginRequest.getPassword());

        if (isValidUser) {
            return new ResponseEntity<>(new LoginResponse("登录成功", JwtUtil.generateToken(loginRequest.getUsername())), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(new LoginResponse("用户名或密码错误", null), HttpStatus.UNAUTHORIZED);
        }
    }

    @GetMapping("/userProfile")
    public ResponseEntity<UserProfileResponse> getUserProfile(@RequestParam String token) {
        if (JwtUtil.isTokenValid(token)) {
            UserHS user = userService.getUserByUsername(JwtUtil.extractUsername(token));
            if (user != null) {
                UserProfileResponse response = new UserProfileResponse(
                        user.getUsername(),
                        user.getNickname(),
                        user.getGender(),
                        user.getPhoneNumber(),
                        user.getEmail(),
                        user.getDepartment(),
                        user.getRole(),
                        user.getCreatedAt()
                );
                if (user.getSuperAdmin()) {
                    response.setDepartment("超级管理员");
                    response.setRole("超级管理员");
                }
                return new ResponseEntity<>(response, HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @PostMapping("/manageUserProfile")
    @JwtVerify
    public ResponseEntity<Object> manageUserProfile(@RequestBody ManageUserProfileRequest userProfileRequest) {
        String username = JwtUtil.extractUsername(userProfileRequest.getToken());
        boolean succeeded = userService.updateUserProfile(username, userProfileRequest);
        if (succeeded) {
            return new ResponseEntity<>(HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    @PostMapping("/changePassword")
    @JwtVerify
    public ResponseEntity<Object> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {
        if (userService.changePassword(JwtUtil.extractUsername(changePasswordRequest.getToken()), changePasswordRequest)) {
            return new ResponseEntity<>(HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    @GetMapping("/getVerificationCode")
    public ResponseEntity<VerificationCodeResponse> getVerificationCode() {
        return new ResponseEntity<>(verificationCodeService.provideVerificationCode(), HttpStatus.OK);
    }


}
