package org.dromara.talk.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.talk.domain.vo.TalkUserVo;
import org.dromara.talk.service.ITalkUserService;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 对话前端认证接口
 *
 * @author Lion Li
 *  2026-01-28
 */
@Slf4j
@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/talk/auth")
@CrossOrigin(origins = "*", maxAge = 3600)
public class TalkAuthController {

    private final ITalkUserService talkUserService;

    /**
     * 登录
     *
     * @param request 登录请求参数，包含username（用户名）和password（密码）
     * @param clientId 客户端ID，用于验证客户端身份
     */
    @PostMapping("/login")
    public R<Map<String, Object>> login(@RequestBody Map<String, String> request, @RequestHeader(value = LoginHelper.CLIENT_KEY, required = false) String clientId) {
        String username = request.get("username");
        String password = request.get("password");

        try {
            Map<String, Object> result = talkUserService.login(username, password, clientId);
            return R.ok(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        StpUtil.logout();
        return R.ok();
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/userInfo")
    public R<TalkUserVo> getUserInfo() {
        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            return R.fail("未登录或登录已过期");
        }
        TalkUserVo user = talkUserService.queryById(userId);
        return R.ok(user);
    }

}
