package com.snack.server.module.chat.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.snack.server.common.Result;
import com.snack.server.constant.LoginType;
import com.snack.server.module.user.entity.User;
import com.snack.server.module.user.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

/**
 * 用户端简易登录（演示 / 调试用，用于获取 Sa-Token）
 */
@Tag(name = "用户认证（简易）")
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserAuthController {

    private final UserMapper userMapper;

    @Operation(summary = "用户登录（获取 token）")
    @PostMapping("/login")
    public Result<LoginResp> login(@RequestBody LoginReq req) {
        if (req.getUsername() == null || req.getPassword() == null) {
            return Result.fail("用户名或密码不能为空");
        }
        User user = userMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<User>()
                        .eq(User::getUsername, req.getUsername())
        );
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }
        if (user.getStatus() != null && user.getStatus() == 0) {
            return Result.fail("账号已被禁用");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(req.getPassword(), user.getPassword())) {
            return Result.fail("用户名或密码错误");
        }

        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();

        LoginResp resp = new LoginResp();
        resp.setToken(token);
        resp.setUserId(user.getId());
        resp.setNickname(user.getNickname());
        return Result.ok(resp);
    }

    @Data
    public static class LoginReq implements Serializable {
        @NotBlank(message = "用户名不能为空")
        @Size(min = 3, max = 50)
        private String username;
        @NotBlank(message = "密码不能为空")
        private String password;
    }

    @Data
    public static class LoginResp implements Serializable {
        private String token;
        private Long userId;
        private String nickname;
    }
}
