// FPSMS-backend/src/main/java/com/ffii/fpsms/modules/stock/entity/PickExecutionIssueRepository.kt
package com.ffii.fpsms.modules.pickOrder.entity 

import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
@Repository
interface PickExecutionIssueRepository : JpaRepository<PickExecutionIssue, Long> {
    fun findByPickOrderIdAndDeletedFalse(pickOrderId: Long): List<PickExecutionIssue>
    fun findByPickOrderLineIdAndDeletedFalse(pickOrderLineId: Long): List<PickExecutionIssue>
    fun findByLotIdAndDeletedFalse(lotId: Long): List<PickExecutionIssue>
    fun findByPickOrderLineIdAndLotIdAndDeletedFalse(
        pickOrderLineId: Long, 
        lotId: Long
    ): List<PickExecutionIssue>
    @Query("""
    SELECT p.issueNo 
    FROM PickExecutionIssue p 
    WHERE p.issueNo LIKE CONCAT('SKO-', :yearMonth, '-%')
    AND p.deleted = false
    ORDER BY p.issueNo DESC
    LIMIT 1
""")
fun findLatestIssueNoByYearMonth(@Param("yearMonth") yearMonth: String): String?

fun findByDeletedFalse(): List<PickExecutionIssue>

// 只返回 Job Order 的 issues (joPickOrderId 不为空)
@Query("""
    SELECT p FROM PickExecutionIssue p 
    WHERE p.joPickOrderId IS NOT NULL 
    AND p.deleted = false
    ORDER BY p.created DESC
""")
fun findJoIssues(): List<PickExecutionIssue>

// 只返回 Delivery Order 的 issues (doPickOrderId 不为空)
@Query("""
    SELECT p FROM PickExecutionIssue p 
    WHERE p.doPickOrderId IS NOT NULL 
    AND p.deleted = false
    ORDER BY p.created DESC
""")
fun findDoIssues(): List<PickExecutionIssue>

// 只返回 Material 的 issues (两者都为空)
@Query("""
    SELECT p FROM PickExecutionIssue p 
    WHERE p.joPickOrderId IS NULL 
    AND p.doPickOrderId IS NULL 
    AND p.deleted = false
    ORDER BY p.created DESC
""")
fun findMaterialIssues(): List<PickExecutionIssue>
}