package com.ffii.fpsms.m18.entity

import com.ffii.core.support.AbstractRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param

interface M18BomShopSyncLogRepository : AbstractRepository<M18BomShopSyncLog, Long> {
    fun findFirstByBomIdOrderByIdDesc(bomId: Long): M18BomShopSyncLog?

    fun findTop100ByBomIdOrderByIdDesc(bomId: Long): List<M18BomShopSyncLog>

    /** Successful M18 udfBomForShop saves only — used for `BOM{item}Vnnn` version allocation. */
    fun findTop100ByBomIdAndSyncedIsTrueOrderByIdDesc(bomId: Long): List<M18BomShopSyncLog>

    fun findFirstByBomIdAndSyncedIsTrueAndRequestFingerprintOrderByIdDesc(
        bomId: Long,
        requestFingerprint: String,
    ): M18BomShopSyncLog?

    fun findFirstByBomIdAndSyncedIsTrueAndM18HeaderCodeOrderByIdDesc(
        bomId: Long,
        m18HeaderCode: String,
    ): M18BomShopSyncLog?

    @Query(
        """
        SELECT l FROM M18BomShopSyncLog l
        WHERE l.deleted = false
        AND (:syncDateStart IS NULL OR l.created >= :syncDateStart)
        AND (:syncDateEnd IS NULL OR l.created <= :syncDateEnd)
        AND (
            :finishedItemCode IS NULL OR :finishedItemCode = ''
            OR LOWER(l.finishedItemCode) LIKE LOWER(CONCAT('%', :finishedItemCode, '%'))
        )
        AND (
            :syncStatus IS NULL OR :syncStatus = '' OR :syncStatus = 'all'
            OR (:syncStatus = 'success' AND l.synced = true)
            OR (:syncStatus = 'failed' AND l.synced = false)
        )
        ORDER BY l.created DESC, l.id DESC
        """,
    )
    fun searchForReport(
        @Param("syncDateStart") syncDateStart: java.time.LocalDateTime?,
        @Param("syncDateEnd") syncDateEnd: java.time.LocalDateTime?,
        @Param("finishedItemCode") finishedItemCode: String?,
        @Param("syncStatus") syncStatus: String?,
    ): List<M18BomShopSyncLog>
}
