package com.honey.honey.repository;

import com.honey.honey.model.Transaction;
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.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.time.Instant;

@Repository
public interface TransactionRepository extends JpaRepository<Transaction, Long> {
    
    /**
     * Finds all transactions for a user, ordered by creation time descending (newest first).
     * Uses index idx_user_id_created_at for optimal performance.
     */
    Page<Transaction> findByUserIdOrderByCreatedAtDesc(Integer userId, Pageable pageable);
    
    /**
     * Batch deletes all transactions older than the specified date (up to batchSize).
     * Returns the number of deleted rows.
     * Note: MySQL requires LIMIT to be used directly in DELETE statements.
     */
    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Query(value = "DELETE FROM transactions WHERE created_at < :cutoffDate LIMIT :batchSize", nativeQuery = true)
    int deleteOldTransactionsBatch(@Param("cutoffDate") Instant cutoffDate, @Param("batchSize") int batchSize);
    
    /**
     * Counts transactions of a specific type for a user.
     */
    long countByUserIdAndType(Integer userId, Transaction.TransactionType type);

    /**
     * Returns sum of transaction amounts per user for the given user IDs (batch, for admin list).
     */
    @Query("SELECT t.userId, COALESCE(SUM(t.amount), 0) FROM Transaction t WHERE t.userId IN :userIds GROUP BY t.userId")
    List<Object[]> sumAmountByUserIdIn(@Param("userIds") List<Integer> userIds);

}

