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

import com.ffii.fpsms.m18.entity.M18DataLogRepository
import com.ffii.fpsms.m18.service.M18DataLogService
import com.ffii.fpsms.modules.deliveryOrder.entity.DeliveryOrder
import com.ffii.fpsms.modules.deliveryOrder.entity.DeliveryOrderRepository
import com.ffii.fpsms.modules.deliveryOrder.entity.models.DeliveryOrderInfo
import com.ffii.fpsms.modules.deliveryOrder.enums.DeliveryOrderStatus
import com.ffii.fpsms.modules.deliveryOrder.web.models.SaveDeliveryOrderRequest
import com.ffii.fpsms.modules.deliveryOrder.web.models.SaveDeliveryOrderResponse
import com.ffii.fpsms.modules.deliveryOrder.web.models.SaveDeliveryOrderStatusRequest
import com.ffii.fpsms.modules.master.service.CurrencyService
import com.ffii.fpsms.modules.master.service.ShopService
import com.ffii.fpsms.modules.user.entity.UserRepository
import com.ffii.fpsms.modules.user.service.UserService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException
import kotlin.jvm.optionals.getOrDefault
import kotlin.jvm.optionals.getOrNull
import com.ffii.fpsms.modules.deliveryOrder.web.models.DoDetailResponse
import com.ffii.fpsms.modules.deliveryOrder.web.models.DoDetailLineResponse
import com.ffii.fpsms.modules.deliveryOrder.web.models.ReleaseDoRequest
import com.ffii.fpsms.modules.pickOrder.web.models.SavePickOrderRequest
import com.ffii.fpsms.modules.pickOrder.web.models.SavePickOrderLineRequest
import com.ffii.fpsms.modules.pickOrder.enums.PickOrderType
import com.ffii.fpsms.modules.pickOrder.service.PickOrderService
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrder
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderRepository
import com.ffii.fpsms.modules.deliveryOrder.enums.DoPickOrderStatus
import java.time.LocalDate
import java.math.BigDecimal
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import java.time.LocalDateTime
import com.ffii.fpsms.modules.deliveryOrder.web.models.AssignByStoreRequest
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderRecord
import com.ffii.fpsms.modules.deliveryOrder.entity.DoPickOrderRecordRepository
@Service
class DoPickOrderService(
    private val doPickOrderRepository: DoPickOrderRepository,
    private val doPickOrderRecordRepository: DoPickOrderRecordRepository
) {
    
    fun getNextTicketNumber(datePrefix: String, storeId: String): String {
        println("🔍 DEBUG: Getting next ticket number for date prefix: $datePrefix, store: $storeId")
        try {
            val sanitizedStoreId = storeId.replace("/", "")
            // ✅ Include store ID in the search pattern
            val searchPattern = "${datePrefix}_${sanitizedStoreId}_"
            val todayTickets = doPickOrderRepository.findByTicketNoStartingWith(searchPattern)
            println("🔍 DEBUG: Found ${todayTickets.size} existing tickets with prefix $searchPattern")
            todayTickets.forEach { ticket ->
                println("�� DEBUG: Existing ticket: ${ticket.ticketNo}, Status: ${ticket.ticketStatus}")
            }
            val nextNumber = (todayTickets.size + 1).toString().padStart(3, '0')
            val ticketNumber = "${datePrefix}_${sanitizedStoreId}_${nextNumber}"
            println("🔍 DEBUG: Generated ticket number: $ticketNumber")
            return ticketNumber
        } catch (e: Exception) {
            println("❌ ERROR in getNextTicketNumber: ${e.message}")
            e.printStackTrace()
            throw e
        }
    }
    fun save(record: DoPickOrder): DoPickOrder {
        return doPickOrderRepository.save(record)
    }
    
    fun findByStoreIdOrderByTruckDepartureTime(storeId: String): List<DoPickOrder> {
        return doPickOrderRepository.findByStoreIdAndTicketStatusOrderByTruckDepartureTimeAsc(
            storeId, DoPickOrderStatus.pending
        )
    }
    
    // Add these missing methods
    fun assignByStore(request: AssignByStoreRequest): MessageResponse {
        // TODO: Implement store-based assignment logic
        return MessageResponse(
            id = null,
            code = null,
            name = null,
            type = null,
            message = "Store-based assignment not implemented yet",
            errorPosition = null,
            entity = null
        )
    }
    
    fun releaseAssignedByStore(request: AssignByStoreRequest): MessageResponse {
        // TODO: Implement store-based release logic
        return MessageResponse(
            id = null,
            code = null,
            name = null,
            type = null,
            message = "Store-based release not implemented yet",
            errorPosition = null,
            entity = null
        )
    }
    fun updateHandledByForPickOrder(pickOrderId: Long, userId: Long): List<DoPickOrder> {
        val doPickOrders = doPickOrderRepository.findByPickOrderId(pickOrderId)
        doPickOrders.forEach { it.handledBy = userId
        it.ticketStatus = DoPickOrderStatus.released }
        return doPickOrderRepository.saveAll(doPickOrders)
    }
    fun completeDoPickOrdersForPickOrder(pickOrderId: Long): List<DoPickOrder> {
        val doPickOrders = doPickOrderRepository.findByPickOrderId(pickOrderId)
        doPickOrders.forEach { 
            it.ticketStatus = DoPickOrderStatus.completed  // ✅ Update status to "completed"
        }
        return doPickOrderRepository.saveAll(doPickOrders)
    }
    
    // ✅ New method to remove do_pick_order records when auto-assigning by store
    fun removeDoPickOrdersForPickOrder(pickOrderId: Long): Int {
        val doPickOrders = doPickOrderRepository.findByPickOrderId(pickOrderId)
        if (doPickOrders.isNotEmpty()) {
            // Mark as deleted instead of physically deleting
            doPickOrders.forEach { 
                it.ticketStatus = DoPickOrderStatus.completed
                it.deleted = true }
            doPickOrderRepository.saveAll(doPickOrders)
            return doPickOrders.size
        }
        return 0
    }

    fun saveRecord(record: DoPickOrderRecord): DoPickOrderRecord {
        return doPickOrderRecordRepository.save(record)
    }
    
    // ✅ Add method to update DoPickOrderRecord status
    fun updateRecordHandledByForPickOrder(pickOrderId: Long, userId: Long): List<DoPickOrderRecord> {
        val doPickOrderRecords = doPickOrderRecordRepository.findByPickOrderId(pickOrderId)
        doPickOrderRecords.forEach { 
            it.handledBy = userId
            it.ticketStatus = DoPickOrderStatus.released
        }
        return doPickOrderRecordRepository.saveAll(doPickOrderRecords)
    }
    
    // ✅ Add method to complete DoPickOrderRecord
    fun completeDoPickOrderRecordsForPickOrder(pickOrderId: Long): List<DoPickOrderRecord> {
        val doPickOrderRecords = doPickOrderRecordRepository.findByPickOrderId(pickOrderId)
        doPickOrderRecords.forEach { 
            it.ticketStatus = DoPickOrderStatus.completed
        }
        return doPickOrderRecordRepository.saveAll(doPickOrderRecords)
    }
    
    // Add method to find do_pick_order records by pick order ID
    fun findByPickOrderId(pickOrderId: Long): List<DoPickOrder> {
        return doPickOrderRepository.findByPickOrderId(pickOrderId)
    }
}