package ru.soune.nocopy.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import ru.soune.nocopy.entity.tarif.TariffInfo;
import ru.soune.nocopy.entity.tarif.TariffTimeTerm;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface TariffInfoRepository extends JpaRepository<TariffInfo, String> {
    @Query("SELECT t FROM TariffInfo t WHERE t.autoRenewal = true AND t.endTariff <= :date")
    List<TariffInfo> findForAutoRenewal(@Param("date") LocalDateTime date);

    @Query("""
        SELECT COUNT(u.Id)
        FROM User u
        WHERE (:activeOnly = false OR u.isActive = true)
          AND (:companyOnly = false OR u.company IS NOT NULL)
    """)
    Long getTotalUsersCount(
            @Param("activeOnly") boolean activeOnly,
            @Param("companyOnly") boolean companyOnly
    );

    @Query("""
        SELECT COUNT(u.Id)
        FROM User u
        WHERE (:activeOnly = false OR u.isActive = true)
    """)
    Long getTotalUsersCount(@Param("activeOnly") boolean activeOnly);

    @Query(value = """
    SELECT 
        t.tariff_name,
        COUNT(u.id) as user_count,
        (COUNT(u.id) * 100.0) / NULLIF(
            (SELECT COUNT(*) FROM users u2 
             WHERE (:activeOnly = false OR u2.is_active = true)
               AND u2.personal_tariff_info_id IS NOT NULL
            ), 0
        ) as usage_percent
    FROM users u
    INNER JOIN tariff_info pti ON u.personal_tariff_info_id = pti.id
    INNER JOIN tariff t ON pti.tariff_id = t.id
    WHERE (:activeOnly = false OR u.is_active = true)
    GROUP BY t.id, t.tariff_name
    ORDER BY user_count DESC
""", nativeQuery = true)
    List<Object[]> getTariffStatisticsNative(@Param("activeOnly") boolean activeOnly);

    @Query("""
        SELECT COUNT(ti.id)
        FROM TariffInfo ti
        WHERE ti.endTariff >= CURRENT_TIMESTAMP
          AND (:term IS NULL OR ti.tariff.tariffTerm = :term)
    """)
    Long getCurrentActiveSubscriptions(@Param("term") TariffTimeTerm term);

    @Query("""
        SELECT ti
        FROM TariffInfo ti
        WHERE (:term IS NULL OR ti.tariff.tariffTerm = :term)
        ORDER BY ti.startTariff
    """)
    List<TariffInfo> getAllTariffInfosForAnalysis(@Param("term") TariffTimeTerm term);
}
