package tech.easyflow.usercenter.controller.agent;

import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.agent.entity.Agent;
import tech.easyflow.agent.security.AgentVisibilityQueryHelper;
import tech.easyflow.agent.service.AgentService;
import tech.easyflow.ai.enums.PublishStatus;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.usercenter.model.agent.UcAgentListItemVo;

import java.util.Collections;
import java.util.List;

/**
 * 用户中心 Agent 查询接口。
 */
@RestController
@RequestMapping("/userCenter/agent")
@UsePermission(moduleName = "/api/v1/agent")
public class UcAgentController {

    private final AgentService agentService;
    private final AgentVisibilityQueryHelper agentVisibilityQueryHelper;

    /**
     * 创建用户中心 Agent 控制器。
     *
     * @param agentService Agent 服务
     * @param agentVisibilityQueryHelper Agent 可见性查询助手
     */
    public UcAgentController(AgentService agentService,
                             AgentVisibilityQueryHelper agentVisibilityQueryHelper) {
        this.agentService = agentService;
        this.agentVisibilityQueryHelper = agentVisibilityQueryHelper;
    }

    /**
     * 查询当前用户可见且已发布的 Agent。
     *
     * @return Agent 列表项
     */
    @GetMapping("/list")
    public Result<List<UcAgentListItemVo>> list() {
        requireCurrentAccount();
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(
                        Agent::getId,
                        Agent::getPublishedSnapshotJson
                )
                .eq(Agent::getStatus, 1)
                .eq(Agent::getPublishStatus, PublishStatus.PUBLISHED.getCode());
        agentVisibilityQueryHelper.applyReadableAccess(queryWrapper);
        queryWrapper.orderBy(Agent::getModified, false);
        List<Agent> agents = agentService.list(queryWrapper);
        if (agents == null || agents.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        return Result.ok(agents.stream()
                .map(agent -> toListItem(agent, agentService.fromSnapshot(agent.getPublishedSnapshotJson())))
                .toList());
    }

    /**
     * 获取并校验当前登录账号。
     *
     * @return 当前登录账号
     * @throws BusinessException 登录信息失效时抛出
     */
    protected LoginAccount requireCurrentAccount() {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        if (account == null || account.getTenantId() == null) {
            throw new BusinessException("当前登录状态失效，请重新登录后再试");
        }
        return account;
    }

    /**
     * 将已发布快照转换为最小用户端列表项。
     *
     * @param liveAgent 当前 Agent 记录
     * @param publishedAgent 已发布 Agent 快照
     * @return 用户端列表项
     */
    private UcAgentListItemVo toListItem(Agent liveAgent, Agent publishedAgent) {
        return new UcAgentListItemVo(
                liveAgent.getId(),
                publishedAgent.getName(),
                publishedAgent.getDescription(),
                publishedAgent.getAvatar()
        );
    }
}
