package com.ffii.fpsms.modules.deliveryOrder.entity

import com.ffii.core.support.AbstractRepository
import com.ffii.fpsms.modules.deliveryOrder.entity.models.DeliveryOrderInfo
import com.ffii.fpsms.modules.deliveryOrder.enums.DeliveryOrderStatus
import com.ffii.fpsms.modules.deliveryOrder.enums.DoPickOrderStatus
import com.ffii.fpsms.modules.master.entity.projections.SearchId
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.io.Serializable
import java.time.LocalDateTime
import java.time.LocalDate

@Repository
interface DoPickOrderRecordRepository : JpaRepository<DoPickOrderRecord, Long> {
    fun findByPickOrderId(pickOrderId: Long): List<DoPickOrderRecord>
    fun findByTicketNoStartingWith(ticketPrefix: String): List<DoPickOrderRecord>

    @Query("""
        SELECT dpor.deliveryNoteCode from DoPickOrderRecord dpor
        WHERE dpor.deliveryNoteCode like :prefix%
        ORDER BY dpor.deliveryNoteCode desc limit 1
    """)
    fun findLatestDeliveryNoteCodeByPrefix(prefix: String): String?

    fun findByStoreIdAndRequiredDeliveryDateAndTicketStatusIn(storeId: String, requiredDeliveryDate: LocalDate, ticketStatus: List<DoPickOrderStatus>): List<DoPickOrderRecord>
    fun findByHandledByAndTicketStatusAndDeletedFalse(handledBy: Long, ticketStatus: DoPickOrderStatus): List<DoPickOrderRecord>

    fun findByTicketStatusAndDeletedFalse(ticketStatus: DoPickOrderStatus): List<DoPickOrderRecord>

    @Query("SELECT d FROM DoPickOrderRecord d WHERE d.deleted = false ORDER BY d.ticketReleaseTime DESC NULLS LAST")
    fun findAllByDeletedFalseOrderByTicketReleaseTimeDesc(): List<DoPickOrderRecord>

    @Query("SELECT d FROM DoPickOrderRecord d WHERE d.deleted = false AND d.requiredDeliveryDate BETWEEN :startDate AND :endDate ORDER BY d.ticketReleaseTime DESC NULLS LAST")
    fun findAllByDeletedFalseAndRequiredDeliveryDateBetween(
        @Param("startDate") startDate: LocalDate,
        @Param("endDate") endDate: LocalDate
    ): List<DoPickOrderRecord>
}