package com.corewing.app.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.corewing.app.common.Result;
import com.corewing.app.dto.LoginRequest;
import com.corewing.app.dto.RegisterRequest;
import com.corewing.app.dto.SendCodeRequest;
import com.corewing.app.dto.UpdatePasswordRequest;
import com.corewing.app.entity.User;
import com.corewing.app.service.UserService;
import com.corewing.app.service.VerifyCodeService;
import com.corewing.app.util.I18nUtil;
import com.corewing.app.util.IpUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 应用用户 Controller
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final VerifyCodeService verifyCodeService;

    public UserController(UserService userService, VerifyCodeService verifyCodeService) {
        this.userService = userService;
        this.verifyCodeService = verifyCodeService;
    }

    /**
     * 发送验证码
     */
    @PostMapping("/sendCode")
    public Result<String> sendCode(@RequestBody SendCodeRequest request) {
        try {
            boolean success = verifyCodeService.sendCode(request.getAccount(), request.getType());
            if (success) {
                return Result.success(I18nUtil.getMessage("user.code.send.success"));
            }
            return Result.error(I18nUtil.getMessage("user.code.send.failed"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录（支持用户名/邮箱/手机号）
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        try {
            String token = userService.login(request.getAccount(), request.getPassword());

            // 更新登录IP和归属地
            User user = userService.getByAccount(request.getAccount());
            String loginIp = IpUtil.getClientIp(httpRequest);
            userService.updateLoginInfo(user.getId(), loginIp);

            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userId", user.getId());
            data.put("username", user.getUsername());

            return Result.success(I18nUtil.getMessage("user.login.success"), data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户注册（需要验证码）
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterRequest request, HttpServletRequest httpRequest) {
        try {
            User user = new User();
            user.setUsername(request.getUsername());
            user.setPassword(request.getPassword());
            user.setEmail(request.getEmail());
            user.setTelephone(request.getTelephone());
            user.setAvatar(request.getAvatar());

            // 获取注册IP
            String registerIp = IpUtil.getClientIp(httpRequest);
            userService.register(user, request.getCode(), registerIp);
            return Result.success(I18nUtil.getMessage("user.register.success"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success(I18nUtil.getMessage("user.logout.success"));
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);
        // 隐藏密码
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user != null) {
            // 隐藏密码
            user.setPassword(null);
            return Result.success(user);
        }
        return Result.error(I18nUtil.getMessage("user.not.found"));
    }

    /**
     * 更新用户信息
     */
    @PutMapping
    public Result<String> update(@RequestBody User user) {
        // 不允许通过此接口修改密码
        user.setPassword(null);

        boolean success = userService.updateById(user);
        if (success) {
            return Result.success(I18nUtil.getMessage("user.update.success"));
        }
        return Result.error(I18nUtil.getMessage("user.update.failed"));
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<String> updatePassword(@RequestBody UpdatePasswordRequest request) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            User user = userService.getById(userId);

            // 验证旧密码
            String oldPasswordMd5 = org.springframework.util.DigestUtils.md5DigestAsHex(
                    request.getOldPassword().getBytes(java.nio.charset.StandardCharsets.UTF_8));

            if (!oldPasswordMd5.equals(user.getPassword())) {
                return Result.error(I18nUtil.getMessage("user.password.old.incorrect"));
            }

            // 更新新密码
            String newPasswordMd5 = org.springframework.util.DigestUtils.md5DigestAsHex(
                    request.getNewPassword().getBytes(java.nio.charset.StandardCharsets.UTF_8));

            user.setPassword(newPasswordMd5);
            userService.updateById(user);

            return Result.success(I18nUtil.getMessage("user.password.update.success"));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
