package com.honey.honey.repository;

import com.honey.honey.model.UserA;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserARepository extends JpaRepository<UserA, Integer>, JpaSpecificationExecutor<UserA> {
    /**
     * Users with id in [fromId, toId] for notification broadcast (paged).
     */
    @Query("SELECT u FROM UserA u WHERE u.id >= :fromId AND u.id <= :toId ORDER BY u.id")
    Page<UserA> findByIdBetween(@Param("fromId") int fromId, @Param("toId") int toId, Pageable pageable);

    /**
     * Max user id for default broadcast range (1 to latest).
     */
    @Query("SELECT COALESCE(MAX(u.id), 0) FROM UserA u")
    int getMaxId();

    Optional<UserA> findByTelegramId(Long telegramId);
    
    /**
     * Counts users registered after the specified Unix timestamp (seconds).
     */
    @Query("SELECT COUNT(u) FROM UserA u WHERE u.dateReg >= :timestamp")
    long countByDateRegAfter(@Param("timestamp") Integer timestamp);
    
    /**
     * Counts users who logged in after the specified Unix timestamp (seconds).
     */
    @Query("SELECT COUNT(u) FROM UserA u WHERE u.dateLogin >= :timestamp")
    long countByDateLoginAfter(@Param("timestamp") Integer timestamp);
    
    /**
     * Counts users registered between two Unix timestamps (seconds).
     */
    @Query("SELECT COUNT(u) FROM UserA u WHERE u.dateReg >= :start AND u.dateReg < :end")
    long countByDateRegBetween(@Param("start") Integer start, @Param("end") Integer end);
    
    /**
     * Counts users who logged in between two Unix timestamps (seconds).
     */
    @Query("SELECT COUNT(u) FROM UserA u WHERE u.dateLogin >= :start AND u.dateLogin < :end")
    long countByDateLoginBetween(@Param("start") Integer start, @Param("end") Integer end);

    long countByBotActiveIsFalse();

    long countByBotActiveIsTrue();

    /**
     * Paged users in id range for broadcast when skipping inactive-bot users.
     */
    @Query("SELECT u FROM UserA u WHERE u.id >= :fromId AND u.id <= :toId AND u.botActive = true ORDER BY u.id")
    Page<UserA> findByIdBetweenAndBotActiveTrue(@Param("fromId") int fromId, @Param("toId") int toId, Pageable pageable);
}


