package com.gcsc.connection.apikey.repository;

import com.gcsc.connection.apikey.entity.SnpApiKey;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
import java.util.Optional;

public interface SnpApiKeyRepository extends JpaRepository<SnpApiKey, Long> {

    Optional<SnpApiKey> findByApiKey(String apiKey);

    List<SnpApiKey> findByUserUserId(Long userId);

    List<SnpApiKey> findByApiKeyPrefix(String apiKeyPrefix);

    /** 유효한 API 키가 존재하는 사용자 수 */
    @Query(value = "SELECT COUNT(DISTINCT user_id) FROM common.snp_api_key " +
        "WHERE status = 'ACTIVE' AND (expires_at IS NULL OR expires_at > NOW())", nativeQuery = true)
    long countUsersWithActiveKey();

    /** 테넌트별 API 키 현황 (전체 키 수, 활성 키 수) */
    @Query(value = "SELECT t.tenant_name, COUNT(k.api_key_id), " +
        "COUNT(CASE WHEN k.status = 'ACTIVE' THEN 1 END) " +
        "FROM common.snp_api_key k " +
        "JOIN common.snp_user u ON k.user_id = u.user_id " +
        "JOIN common.snp_tenant t ON u.tenant_id = t.tenant_id " +
        "GROUP BY t.tenant_name", nativeQuery = true)
    List<Object[]> findTenantApiKeyStats();
}
