package tech.easyflow.skill.publish;

import org.springframework.stereotype.Service;
import tech.easyflow.ai.publish.AiResourceLifecycleService;
import tech.easyflow.approval.entity.vo.ApprovalActionResult;
import tech.easyflow.approval.enums.ApprovalActionType;
import tech.easyflow.approval.enums.ApprovalResourceType;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.math.BigInteger;

/**
 * Skill 发布生命周期应用服务。
 */
@Service
public class SkillPublishAppService {

    private final AiResourceLifecycleService aiResourceLifecycleService;

    /**
     * 创建 Skill 发布应用服务。
     *
     * @param aiResourceLifecycleService AI 资源生命周期服务
     */
    public SkillPublishAppService(AiResourceLifecycleService aiResourceLifecycleService) {
        this.aiResourceLifecycleService = aiResourceLifecycleService;
    }

    /**
     * 提交 Skill 发布审批。
     *
     * @param id Skill ID
     * @param applicationReason 发布说明
     * @return 审批动作结果
     */
    public ApprovalActionResult submitPublishApproval(BigInteger id, String applicationReason) {
        if (applicationReason == null || applicationReason.isBlank()) {
            throw new BusinessException("发布说明不能为空");
        }
        String normalizedReason = applicationReason.trim();
        if (normalizedReason.length() > 500) {
            throw new BusinessException("发布说明不能超过 500 个字符");
        }
        return submit(id, ApprovalActionType.PUBLISH, normalizedReason);
    }

    /**
     * 提交 Skill 下线审批。
     *
     * @param id Skill ID
     * @return 审批动作结果
     */
    public ApprovalActionResult submitOfflineApproval(BigInteger id) {
        return submit(id, ApprovalActionType.OFFLINE, null);
    }

    /**
     * 提交 Skill 删除审批。
     *
     * @param id Skill ID
     * @return 审批动作结果
     */
    public ApprovalActionResult submitDeleteApproval(BigInteger id) {
        return submit(id, ApprovalActionType.DELETE, null);
    }

    private ApprovalActionResult submit(BigInteger id, ApprovalActionType actionType, String applicationReason) {
        if (id == null) {
            throw new BusinessException("Skill 审批时资源ID不能为空");
        }
        tech.easyflow.common.entity.LoginAccount account = SaTokenUtil.getLoginAccount();
        if (account == null || account.getId() == null || account.getTenantId() == null) {
            throw new BusinessException(401, 401, "未登录或登录态无效");
        }
        return aiResourceLifecycleService.submitAction(
                ApprovalResourceType.SKILL.getCode(),
                id,
                actionType.getCode(),
                account.getId(),
                applicationReason
        );
    }
}
