package com.ffii.fpsms.modules.deliveryOrder.service

import com.ffii.core.support.JdbcDao
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderRepository
import com.ffii.fpsms.modules.deliveryOrder.enums.DoPickOrderStatus
import com.ffii.fpsms.modules.deliveryOrder.web.models.LaneBtn
import com.ffii.fpsms.modules.deliveryOrder.web.models.LaneRow
import com.ffii.fpsms.modules.deliveryOrder.web.models.StoreLaneSummary
import org.springframework.stereotype.Service
import java.time.LocalDate

@Service
class DoPickOrderQueryService(
    private val doPickOrderRepository: DoPickOrderRepository,
    private val jdbcDao: JdbcDao
) {
    
    fun getSummaryByStore(storeId: String, requiredDate: LocalDate?): StoreLaneSummary {
        val targetDate = requiredDate ?: LocalDate.now()
        println("🔍 DEBUG: Getting summary for store=$storeId, date=$targetDate")
        
        val actualStoreId = when (storeId) {
            "2/F" -> "2/F"
            "4/F" -> "4/F"
            else -> storeId
        }
        
        val allRecords = doPickOrderRepository.findByStoreIdAndRequiredDeliveryDateAndTicketStatusIn(
            actualStoreId,
            targetDate,
            listOf(DoPickOrderStatus.pending, DoPickOrderStatus.released, DoPickOrderStatus.completed)
        )
        
        println("🔍 DEBUG: Found ${allRecords.size} records for date $targetDate")
        
        val filteredRecords = allRecords.filter { doPickOrder ->
            val hasNonIssueLines = checkDoPickOrderHasNonIssueLines(doPickOrder.id!!)
            if (!hasNonIssueLines) {
                println("🔍 DEBUG: Filtering out DoPickOrder ${doPickOrder.id} - all lines are issues")
            }
            hasNonIssueLines
        }
        
        println("🔍 DEBUG: After filtering, ${filteredRecords.size} records remain")
        
        val grouped = filteredRecords.groupBy { it.truckDepartureTime to it.truckLanceCode }
            .mapValues { (_, list) ->
                LaneBtn(
                    truckLanceCode = list.first().truckLanceCode ?: "",
                    unassigned = list.count { it.handledBy == null },
                    total = list.size
                )
            }
        
        val timeGroups = grouped.entries
            .groupBy { it.key.first }
            .mapValues { (_, entries) ->
                entries.map { it.value }
                    .sortedByDescending { it.unassigned }
                    .take(3)
            }
            .filterValues { lanes -> lanes.any { it.unassigned > 0 } }
            .toSortedMap(compareBy { it })
            .entries.take(4)
            .map { (time, lanes) ->
                LaneRow(
                    truckDepartureTime = time?.toString() ?: "",
                    lanes = lanes
                )
            }
        
        return StoreLaneSummary(storeId = storeId, rows = timeGroups)
    }
    
    private fun checkDoPickOrderHasNonIssueLines(doPickOrderId: Long): Boolean {
        return try {
            val totalLinesSql = """
                SELECT COUNT(*) as total_lines
                FROM fpsmsdb.do_pick_order_line dpol
                WHERE dpol.do_pick_order_id = :doPickOrderId 
                AND dpol.deleted = 0
            """.trimIndent()
            
            val totalLinesResult = jdbcDao.queryForList(totalLinesSql, mapOf("doPickOrderId" to doPickOrderId))
            val totalLines = (totalLinesResult.firstOrNull()?.get("total_lines") as? Number)?.toInt() ?: 0
            
            if (totalLines == 0) {
                return true
            }
            
            val nonIssueLinesSql = """
                SELECT COUNT(*) as non_issue_lines
                FROM fpsmsdb.do_pick_order_line dpol
                WHERE dpol.do_pick_order_id = :doPickOrderId 
                AND dpol.deleted = 0
                AND (dpol.status IS NULL OR dpol.status != 'issue')
            """.trimIndent()
            
            val nonIssueLinesResult = jdbcDao.queryForList(nonIssueLinesSql, mapOf("doPickOrderId" to doPickOrderId))
            val nonIssueLines = (nonIssueLinesResult.firstOrNull()?.get("non_issue_lines") as? Number)?.toInt() ?: 0
            
            nonIssueLines > 0
        } catch (e: Exception) {
            println("❌ Error checking non-issue lines: ${e.message}")
            true
        }
    }
}