package com.mini.capi.biz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mini.capi.biz.domain.BizHomeUser;
import com.mini.capi.biz.service.BizHomeUserService;
import com.mini.capi.model.auth.LoginRequest;
import com.mini.capi.model.info.TodoHandleDTO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/biz")
public class LoginController {


    @Resource
    private BizHomeUserService userService;


    /**
     * 登录
     */
    @PostMapping("/userLogin")
    public Map<String, Object> userLogin(@RequestBody LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        try {
            String username = loginRequest.getUsername();
            String password = loginRequest.getPassword();

            QueryWrapper<BizHomeUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", username).eq("password", password);
            BizHomeUser user = userService.getOne(queryWrapper);
            if (user != null) {
                request.getSession().setAttribute("currentUser", user);
                // 3.3 返回成功响应
                result.put("success", true);
                result.put("message", "登录成功");
            } else {
                result.put("success", false);
                result.put("message", "账号或密码错误");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "服务器内部错误," + e.getMessage());
        }
        return result;
    }


    /**
     * 处理退出登录请求
     * 对应前端 fetch('/logout', {method: 'POST'})
     */
    @PostMapping("/logout")
    public ResponseEntity<Void> logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {
            // 3. 清除Session中的用户信息
            if (session != null) {
                session.removeAttribute("currentUser"); // 清除之前存入的currentUser
                session.invalidate(); // 使Session失效
            }
            // 5. 返回成功响应（200 OK）
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 处理异常情况
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}
