package com.nanri.aiimage.modules.ziniao.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopKeyEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ZiniaoApiKeyProvider {

    private final ShopKeyMapper shopKeyMapper;

    public List<String> listApiKeys() {
        return shopKeyMapper.selectList(new LambdaQueryWrapper<ShopKeyEntity>()
                        .orderByDesc(ShopKeyEntity::getId))
                .stream()
                .map(ShopKeyEntity::getZiniaoToken)
                .filter(token -> token != null && !token.isBlank())
                .map(String::trim)
                .map(token -> token.regionMatches(true, 0, "Bearer ", 0, 7) ? token.substring(7).trim() : token)
                .filter(token -> !token.isBlank())
                .distinct()
                .toList();
    }

    public String getRequiredApiKey() {
        List<String> keys = listApiKeys();
        if (keys.isEmpty()) {
            throw new BusinessException("紫鸟 apiKey 未配置，请先在店铺密钥管理中维护可用令牌");
        }
        return keys.get(0);
    }

    public boolean hasApiKey() {
        Long total = shopKeyMapper.selectCount(new LambdaQueryWrapper<ShopKeyEntity>());
        return total != null && total > 0;
    }
}
