package de.cannamanage.service.repository;

import de.cannamanage.domain.entity.Distribution;
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.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.UUID;

@Repository
public interface DistributionRepository extends JpaRepository<Distribution, UUID> {

    @Query("SELECT COALESCE(SUM(d.quantityGrams), 0) FROM Distribution d " +
           "WHERE d.memberId = :memberId AND d.distributedAt >= :dayStart AND d.distributedAt < :dayEnd")
    BigDecimal sumQuantityByMemberAndDay(
        @Param("memberId") UUID memberId,
        @Param("dayStart") Instant dayStart,
        @Param("dayEnd") Instant dayEnd
    );

    long countByTenantIdAndDistributedAtAfter(UUID tenantId, Instant after);

    @Query("SELECT COALESCE(SUM(d.quantityGrams), 0) FROM Distribution d " +
           "WHERE d.tenantId = :tenantId AND d.distributedAt >= :after")
    BigDecimal sumGramsByTenantIdAndDistributedAtAfter(
        @Param("tenantId") UUID tenantId,
        @Param("after") Instant after
    );

    /**
     * Find all distributions for a tenant within a time range.
     */
    List<Distribution> findByTenantIdAndDistributedAtBetween(UUID tenantId, Instant start, Instant end);

    /**
     * Find all distributions for a specific batch (for recall reports).
     */
    List<Distribution> findByTenantIdAndBatchId(UUID tenantId, UUID batchId);

    /**
     * Count distributions for a specific member within a tenant.
     */
    long countByTenantIdAndMemberId(UUID tenantId, UUID memberId);

    /**
     * Find the most recent distribution for a member.
     */
    @Query("SELECT d FROM Distribution d WHERE d.tenantId = :tenantId AND d.memberId = :memberId " +
           "ORDER BY d.distributedAt DESC LIMIT 1")
    Distribution findLatestByTenantIdAndMemberId(@Param("tenantId") UUID tenantId, @Param("memberId") UUID memberId);

    /**
     * Find the 5 most recent distributions for a specific member (portal dashboard).
     */
    List<Distribution> findTop5ByMemberIdAndTenantIdOrderByDistributedAtDesc(UUID memberId, UUID tenantId);

    /**
     * Paginated distribution history for a member, newest first (portal history).
     */
    Page<Distribution> findByMemberIdAndTenantIdOrderByDistributedAtDesc(UUID memberId, UUID tenantId, Pageable pageable);
}
