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.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ZiniaoApiKeyProvider {

    private final ShopKeyMapper shopKeyMapper;

    public List<ApiKeyAccount> listApiKeyAccounts() {
        List<ShopKeyEntity> entities = shopKeyMapper.selectList(new LambdaQueryWrapper<ShopKeyEntity>()
                .orderByDesc(ShopKeyEntity::getId));
        Map<String, String> accountByApiKey = new LinkedHashMap<>();
        for (ShopKeyEntity entity : entities) {
            String apiKey = normalizeApiKey(entity == null ? null : entity.getZiniaoToken());
            if (apiKey == null) {
                continue;
            }
            String accountName = entity.getZiniaoAccountName() == null ? null : entity.getZiniaoAccountName().trim();
            if (!accountByApiKey.containsKey(apiKey)) {
                accountByApiKey.put(apiKey, accountName);
                continue;
            }
            String existingName = accountByApiKey.get(apiKey);
            if ((existingName == null || existingName.isBlank()) && accountName != null && !accountName.isBlank()) {
                accountByApiKey.put(apiKey, accountName);
            }
        }
        return accountByApiKey.entrySet().stream()
                .map(entry -> new ApiKeyAccount(entry.getKey(), entry.getValue()))
                .toList();
    }

    public List<String> listApiKeys() {
        return listApiKeyAccounts().stream()
                .map(ApiKeyAccount::apiKey)
                .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;
    }

    private String normalizeApiKey(String token) {
        if (token == null || token.isBlank()) {
            return null;
        }
        String normalized = token.trim();
        if (normalized.regionMatches(true, 0, "Bearer ", 0, 7)) {
            normalized = normalized.substring(7).trim();
        }
        return normalized.isBlank() ? null : normalized;
    }

    public record ApiKeyAccount(String apiKey, String accountName) {
    }
}
