package com.dora.service;

import com.dora.dto.ApiKeyDTO;
import com.dora.entity.ApiKey;
import com.dora.entity.User;
import com.dora.mapper.ApiKeyMapper;
import com.dora.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * API密钥服务类
 */
@Service
public class ApiKeyService {

    @Autowired
    private ApiKeyMapper apiKeyMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 生成API密钥
     * 
     * <p>新规则：所有用户都可以生成API密钥
     * <ul>
     *   <li>会员：可以生成API密钥，享受会员权益</li>
     *   <li>非会员：可以生成API密钥，通过积分使用服务</li>
     * </ul>
     */
    @Transactional
    public ApiKeyDTO generateApiKey(Long userId) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 不再限制会员身份，所有用户都可以生成API密钥

        // 检查是否已有活跃的API密钥
        ApiKey existingKey = apiKeyMapper.selectByUserId(userId);
        if (existingKey != null) {
            throw new RuntimeException("用户已有API密钥，请先删除现有密钥");
        }

        // 检查是否存在被逻辑删除的记录，如果存在则恢复
        ApiKey deletedKey = apiKeyMapper.selectByUserIdIncludeDeleted(userId);
        if (deletedKey != null) {
            // 恢复被删除的记录
            deletedKey.setKeyValue(generateUniqueKey());
            deletedKey.setIsActive(true);
            deletedKey.setIsDeleted(false);
            deletedKey.setUpdateTime(LocalDateTime.now());
            apiKeyMapper.update(deletedKey);
            return convertToDTO(deletedKey, user);
        }

        // 生成新的API密钥
        ApiKey apiKey = new ApiKey();
        apiKey.setUserId(userId);
        apiKey.setKeyValue(generateUniqueKey());
        apiKey.setIsActive(true);
        apiKey.setCreateTime(LocalDateTime.now());
        apiKey.setUpdateTime(LocalDateTime.now());
        apiKey.setIsDeleted(false);

        apiKeyMapper.insert(apiKey);

        return convertToDTO(apiKey, user);
    }

    /**
     * 刷新API密钥
     * 
     * <p>所有用户都可以刷新API密钥
     */
    @Transactional
    public ApiKeyDTO refreshApiKey(Long userId) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 不再限制会员身份

        // 查找现有API密钥
        ApiKey existingKey = apiKeyMapper.selectByUserId(userId);
        if (existingKey == null) {
            throw new RuntimeException("用户没有API密钥，请先生成");
        }

        // 生成新的密钥值
        existingKey.setKeyValue(generateUniqueKey());
        existingKey.setUpdateTime(LocalDateTime.now());

        apiKeyMapper.update(existingKey);

        return convertToDTO(existingKey, user);
    }

    /**
     * 删除API密钥
     */
    @Transactional
    public void deleteApiKey(Long userId) {
        ApiKey existingKey = apiKeyMapper.selectByUserId(userId);
        if (existingKey == null) {
            throw new RuntimeException("用户没有API密钥");
        }

        apiKeyMapper.deleteByUserId(userId);
    }

    /**
     * 获取用户的API密钥信息
     */
    public ApiKeyDTO getApiKey(Long userId) {
        ApiKey apiKey = apiKeyMapper.selectByUserId(userId);
        if (apiKey == null) {
            return null;
        }

        User user = userMapper.selectById(userId);
        return convertToDTO(apiKey, user);
    }

    /**
     * 验证API密钥（会员专用，已废弃）
     * @deprecated 建议使用 validateApiKeyForNonMember 方法，支持所有用户使用积分
     */
    @Deprecated
    public User validateApiKey(String keyValue) {
        ApiKey apiKey = apiKeyMapper.selectByKeyValue(keyValue);
        if (apiKey == null || !apiKey.getIsActive()) {
            return null;
        }

        User user = userMapper.selectById(apiKey.getUserId());
        if (user == null) {
            return null;
        }

        // 检查用户是否为会员
        if (user.getRole() < 2) {
            return null;
        }

        // 检查会员是否过期
        if (user.getMembershipExpiresAt() != null && 
            user.getMembershipExpiresAt().isBefore(LocalDateTime.now())) {
            return null;
        }

        // 更新最后使用时间
        apiKey.setLastUsedAt(LocalDateTime.now());
        apiKeyMapper.update(apiKey);

        return user;
    }

    /**
     * 验证API密钥（支持非会员用户）
     * 
     * <p>新的API Key验证逻辑：
     * <ul>
     *   <li>不再限制会员身份，所有用户都可以通过API Key使用服务</li>
     *   <li>用户只需要有足够的积分即可调用AI服务</li>
     *   <li>会员和非会员的区别仅在于充值优惠和功能权限</li>
     * </ul>
     * 
     * @param keyValue API密钥值
     * @return 验证成功返回User对象，失败返回null
     */
    public User validateApiKeyForNonMember(String keyValue) {
        if (keyValue == null || keyValue.trim().isEmpty()) {
            return null;
        }

        ApiKey apiKey = apiKeyMapper.selectByKeyValue(keyValue);
        if (apiKey == null || !apiKey.getIsActive()) {
            return null;
        }

        User user = userMapper.selectById(apiKey.getUserId());
        if (user == null) {
            return null;
        }

        // 不再检查会员身份，所有用户都可以使用API Key
        // 只要有积分就可以调用服务

        // 更新最后使用时间
        apiKey.setLastUsedAt(LocalDateTime.now());
        apiKeyMapper.update(apiKey);

        return user;
    }

    /**
     * API密钥验证结果
     */
    public static class ApiKeyValidationResult {
        private final boolean isValid;
        private final String message;
        
        public ApiKeyValidationResult(boolean isValid, String message) {
            this.isValid = isValid;
            this.message = message;
        }
        
        public boolean isValid() { return isValid; }
        public String getMessage() { return message; }
    }
    
    /**
     * 验证API密钥是否属于指定用户并且有效
     */
    public boolean validateApiKeyForUser(String keyValue, Long userId) {
        ApiKeyValidationResult result = validateApiKeyForUserDetailed(keyValue, userId);
        return result.isValid();
    }
    
    /**
     * 验证API密钥是否属于指定用户并且有效（返回详细结果）
     */
    public ApiKeyValidationResult validateApiKeyForUserDetailed(String keyValue, Long userId) {
        if (keyValue == null || keyValue.trim().isEmpty()) {
            return new ApiKeyValidationResult(false, "API密钥不能为空");
        }
        
        if (userId == null) {
            return new ApiKeyValidationResult(false, "用户ID不能为空");
        }
        
        try {
            // 查找API密钥
            ApiKey apiKey = apiKeyMapper.selectByKeyValue(keyValue);
            if (apiKey == null) {
                return new ApiKeyValidationResult(false, "API密钥不存在，请检查密钥是否正确");
            }
            
            if (!apiKey.getIsActive()) {
                return new ApiKeyValidationResult(false, "API密钥已被禁用，请联系管理员或重新生成");
            }
            
            // 检查API密钥是否属于当前用户
            if (!apiKey.getUserId().equals(userId)) {
                return new ApiKeyValidationResult(false, "API密钥不属于当前用户，无权验证");
            }
            
            // 获取用户信息并验证
            User user = userMapper.selectById(apiKey.getUserId());
            if (user == null) {
                return new ApiKeyValidationResult(false, "用户不存在，API密钥无效");
            }
            
            // 注意：已移除会员验证逻辑，API密钥验证对所有用户免费开放
            
            // 更新最后使用时间
            apiKey.setLastUsedAt(LocalDateTime.now());
            apiKeyMapper.update(apiKey);
            
            return new ApiKeyValidationResult(true, "API密钥验证成功，密钥有效且可正常使用");
        } catch (Exception e) {
            return new ApiKeyValidationResult(false, "API密钥验证失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查API密钥有效期状态（仅限用户自己的API密钥）
     */
    public ApiKeyDTO.ValidityCheckResponse checkApiKeyValidityForUser(String keyValue, Long userId) {
        ApiKeyDTO.ValidityCheckResponse response = new ApiKeyDTO.ValidityCheckResponse();
        
        if (keyValue == null || keyValue.trim().isEmpty() || userId == null) {
            response.setIsValid(false);
            response.setFailureReason("参数无效");
            return response;
        }
        
        try {
            // 查找API密钥
            ApiKey apiKey = apiKeyMapper.selectByKeyValue(keyValue);
            if (apiKey == null) {
                response.setIsValid(false);
                response.setFailureReason("API密钥不存在");
                return response;
            }
            
            // 检查API密钥是否属于当前用户
            if (!apiKey.getUserId().equals(userId)) {
                response.setIsValid(false);
                response.setFailureReason("无权访问此API密钥");
                return response;
            }
            
            // 检查API密钥是否启用
            if (!apiKey.getIsActive()) {
                response.setIsValid(false);
                response.setFailureReason("API密钥已被禁用");
                return response;
            }
            
            // 获取用户信息
            User user = userMapper.selectById(apiKey.getUserId());
            if (user == null) {
                response.setIsValid(false);
                response.setFailureReason("用户不存在");
                return response;
            }
            
            // 检查用户是否为会员
            if (user.getRole() < 2) {
                response.setIsValid(false);
                response.setFailureReason("用户不是会员，无权使用API密钥");
                return response;
            }
            
            // 检查会员是否过期
            boolean isExpired = user.getMembershipExpiresAt() != null && 
                               user.getMembershipExpiresAt().isBefore(LocalDateTime.now());
            if (isExpired) {
                response.setIsValid(false);
                response.setFailureReason("会员已过期");
            } else {
                response.setIsValid(true);
            }
            
            // 构建用户信息
            ApiKeyDTO.ValidityCheckResponse.UserInfo userInfo = new ApiKeyDTO.ValidityCheckResponse.UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setUsername(user.getUsername());
            userInfo.setRole(user.getRole());
            userInfo.setMembershipExpiresAt(user.getMembershipExpiresAt());
            userInfo.setIsMember(user.getRole() >= 2);
            userInfo.setIsExpired(isExpired);
            response.setUserInfo(userInfo);
            
            // 构建API密钥信息（脱敏处理）
            ApiKeyDTO.ValidityCheckResponse.KeyInfo keyInfo = new ApiKeyDTO.ValidityCheckResponse.KeyInfo();
            keyInfo.setKeyValueMasked(maskApiKey(apiKey.getKeyValue()));
            keyInfo.setIsActive(apiKey.getIsActive());
            keyInfo.setCreateTime(apiKey.getCreateTime());
            keyInfo.setLastUsedAt(apiKey.getLastUsedAt());
            response.setKeyInfo(keyInfo);
            
            // 如果API密钥有效，更新最后使用时间
            if (response.getIsValid()) {
                apiKey.setLastUsedAt(LocalDateTime.now());
                apiKeyMapper.update(apiKey);
            }
            
            return response;
            
        } catch (Exception e) {
            response.setIsValid(false);
            response.setFailureReason("验证过程发生错误：" + e.getMessage());
            return response;
        }
    }

    /**
     * 检查API密钥有效期状态（任意API密钥，不推荐使用）
     * @deprecated 建议使用 checkApiKeyValidityForUser 方法，确保权限安全
     */
    @Deprecated
    public ApiKeyDTO.ValidityCheckResponse checkApiKeyValidity(String keyValue) {
        ApiKeyDTO.ValidityCheckResponse response = new ApiKeyDTO.ValidityCheckResponse();
        
        try {
            // 查找API密钥
            ApiKey apiKey = apiKeyMapper.selectByKeyValue(keyValue);
            if (apiKey == null) {
                response.setIsValid(false);
                response.setFailureReason("API密钥不存在");
                return response;
            }
            
            // 检查API密钥是否启用
            if (!apiKey.getIsActive()) {
                response.setIsValid(false);
                response.setFailureReason("API密钥已被禁用");
                return response;
            }
            
            // 获取用户信息
            User user = userMapper.selectById(apiKey.getUserId());
            if (user == null) {
                response.setIsValid(false);
                response.setFailureReason("用户不存在");
                return response;
            }
            
            // 检查用户是否为会员
            if (user.getRole() < 2) {
                response.setIsValid(false);
                response.setFailureReason("用户不是会员，无权使用API密钥");
                return response;
            }
            
            // 检查会员是否过期
            boolean isExpired = user.getMembershipExpiresAt() != null && 
                               user.getMembershipExpiresAt().isBefore(LocalDateTime.now());
            if (isExpired) {
                response.setIsValid(false);
                response.setFailureReason("会员已过期");
            } else {
                response.setIsValid(true);
            }
            
            // 构建用户信息
            ApiKeyDTO.ValidityCheckResponse.UserInfo userInfo = new ApiKeyDTO.ValidityCheckResponse.UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setUsername(user.getUsername());
            userInfo.setRole(user.getRole());
            userInfo.setMembershipExpiresAt(user.getMembershipExpiresAt());
            userInfo.setIsMember(user.getRole() >= 2);
            userInfo.setIsExpired(isExpired);
            response.setUserInfo(userInfo);
            
            // 构建API密钥信息（脱敏处理）
            ApiKeyDTO.ValidityCheckResponse.KeyInfo keyInfo = new ApiKeyDTO.ValidityCheckResponse.KeyInfo();
            keyInfo.setKeyValueMasked(maskApiKey(apiKey.getKeyValue()));
            keyInfo.setIsActive(apiKey.getIsActive());
            keyInfo.setCreateTime(apiKey.getCreateTime());
            keyInfo.setLastUsedAt(apiKey.getLastUsedAt());
            response.setKeyInfo(keyInfo);
            
            // 如果API密钥有效，更新最后使用时间
            if (response.getIsValid()) {
                apiKey.setLastUsedAt(LocalDateTime.now());
                apiKeyMapper.update(apiKey);
            }
            
            return response;
            
        } catch (Exception e) {
            response.setIsValid(false);
            response.setFailureReason("验证过程发生错误：" + e.getMessage());
            return response;
        }
    }
    
    /**
     * API密钥脱敏处理
     */
    private String maskApiKey(String keyValue) {
        if (keyValue == null || keyValue.length() < 8) {
            return "****";
        }
        
        String prefix = keyValue.substring(0, 4);
        String suffix = keyValue.substring(keyValue.length() - 4);
        return prefix + "****" + suffix;
    }

    /**
     * 生成唯一的API密钥
     */
    private String generateUniqueKey() {
        return "ak_" + UUID.randomUUID().toString().replace("-", "").substring(0, 32);
    }

    /**
     * 转换为DTO
     */
    private ApiKeyDTO convertToDTO(ApiKey apiKey, User user) {
        ApiKeyDTO dto = new ApiKeyDTO();
        dto.setKeyValue(apiKey.getKeyValue());
        dto.setIsActive(apiKey.getIsActive());
        dto.setLastUsedAt(apiKey.getLastUsedAt());
        dto.setCreateTime(apiKey.getCreateTime());
        dto.setMembershipExpiresAt(user.getMembershipExpiresAt());
        dto.setUserRole(user.getRole());
        return dto;
    }
} 