package org.dromara.talk.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.system.service.ISysClientService;
import org.dromara.talk.domain.TalkUser;
import org.dromara.talk.domain.vo.TalkUserVo;
import org.dromara.talk.service.ITalkUserService;
import org.springframework.web.bind.annotation.*;

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

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

    private final ITalkUserService talkUserService;
    private final ISysClientService clientService;

    /**
     * 登录
     *
     * @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");

        // 验证 clientId 是否存在
        if (ObjectUtil.isNull(clientId)) {
            log.info("客户端id为空");
            return R.fail("客户端ID不能为空");
        }

        // 查询客户端配置
        SysClientVo client = clientService.queryByClientId(clientId);
        if (ObjectUtil.isNull(client)) {
            log.info("客户端id: {} 不存在", clientId);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!SystemConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }

        // 查询用户（包含密码）
        TalkUser user = talkUserService.queryByUsernameWithPassword(username);
        if (user == null) {
            return R.fail("用户名或密码错误");
        }

        // 验证密码
        if (!password.equals(user.getPassword())) {
            return R.fail("用户名或密码错误");
        }

        // 检查用户状态
        if ("1".equals(user.getStatus())) {
            return R.fail("用户已被停用");
        }

        // 创建 LoginUser 对象（不包含任何权限）
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setUserType(UserType.APP_USER.getUserType());
        loginUser.setMenuPermission(Collections.emptySet());  // 空权限列表
        loginUser.setRolePermission(Collections.emptySet());  // 空角色列表
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());

        // 使用 LoginHelper 登录，使用 sys_client 表中的配置
        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        LoginHelper.login(loginUser, model);

        // 返回token和用户信息（不包含密码）
        TalkUserVo userVo = talkUserService.queryByUsername(username);
        Map<String, Object> result = new HashMap<>();
        result.put("token", StpUtil.getTokenValue());
        result.put("user", userVo);
        result.put("clientId", client.getClientId());

        return R.ok(result);
    }

    /**
     * 退出登录
     */
    @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);
    }

}
