package com.ffii.fpsms.modules.stock.web

import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.purchaseOrder.entity.PurchaseOrderLine
import com.ffii.fpsms.modules.stock.entity.StockOutLine
import com.ffii.fpsms.modules.stock.entity.projection.StockOutLineInfo
import com.ffii.fpsms.modules.stock.service.StockInLineService
import com.ffii.fpsms.modules.stock.service.StockOutLineService
import com.ffii.fpsms.modules.stock.web.model.CreateStockOutLineRequest
import com.ffii.fpsms.modules.stock.web.model.UpdateStockOutLineRequest
import com.ffii.fpsms.modules.stock.web.model.UpdateStockOutLineStatusRequest
import jakarta.validation.Valid
import com.ffii.fpsms.modules.stock.web.model.QrPickBatchSubmitRequest
import org.springframework.web.bind.annotation.*
import com.ffii.fpsms.modules.stock.web.model.CreateStockOutLineWithoutConsoRequest
import com.ffii.fpsms.modules.stock.web.model.UpdateStockOutLineStatusByQRCodeAndLotNoRequest


@RestController
@RequestMapping("/stockOutLine")
class StockOutLineController(
    private val stockOutLineService: StockOutLineService
) {
    @GetMapping("/getByPickOrderLineId/{pickOrderLineId}")
    fun getByPurchaseOrderLineId(@Valid @PathVariable pickOrderLineId: Long): List<StockOutLineInfo> {
        return stockOutLineService.getAllStockOutLineByPickOrderLineId(pickOrderLineId)
    }

    @PostMapping("/create")
    fun create(@Valid @RequestBody request: CreateStockOutLineRequest): MessageResponse {
        return stockOutLineService.create(request)
    }
    @PostMapping("/createWithoutConso")
    fun createWithoutConso(@Valid @RequestBody request: CreateStockOutLineWithoutConsoRequest): MessageResponse {
        return stockOutLineService.createWithoutConso(request)
    }
    @PostMapping("/update")
    fun update(@Valid @RequestBody request: UpdateStockOutLineRequest): MessageResponse {
        println("triggering")
        return stockOutLineService.update(request)
    }

    @PostMapping("/updateStatus")
    fun updateStatus(@Valid @RequestBody request: UpdateStockOutLineStatusRequest): MessageResponse {
        return stockOutLineService.updateStatus(request)
    }

  
    @PostMapping("/batchSubmitList")
    fun batchQrSubmit(@Valid @RequestBody request: QrPickBatchSubmitRequest): MessageResponse {
        return stockOutLineService.newBatchSubmit(request)
    }
    @PostMapping("/updateStatusByQRCodeAndLotNo")
    fun updateStatusByQRCodeAndLotNo(@Valid @RequestBody request: UpdateStockOutLineStatusByQRCodeAndLotNoRequest): MessageResponse {
        val controllerStartTime = System.currentTimeMillis()
        try {
            println("=== CONTROLLER: updateStatusByQRCodeAndLotNo called ===")
            println("⏰ Controller start time: ${java.time.LocalDateTime.now()}")
            println(" Request received:")
            println("  - stockOutLineId: ${request.stockOutLineId}")
            println("   - pickOrderLineId: ${request.pickOrderLineId}")
            println("   - inventoryLotNo: ${request.inventoryLotNo}")
            println("   - itemId: ${request.itemId}")
            println("   - status: ${request.status}")
            
            // Measure service call time
            val serviceCallStart = System.currentTimeMillis()
            val result = stockOutLineService.updateStockOutLineStatusByQRCodeAndLotNo(request)
            val serviceCallTime = System.currentTimeMillis() - serviceCallStart
            println("⏱️ [CONTROLLER] Service call time: ${serviceCallTime}ms (${serviceCallTime / 1000.0}s)")
            
            val controllerTotalTime = System.currentTimeMillis() - controllerStartTime
            println("⏱️ [CONTROLLER] Total controller time: ${controllerTotalTime}ms (${controllerTotalTime / 1000.0}s)")
            println("📊 Controller breakdown: serviceCall=${serviceCallTime}ms, overhead=${controllerTotalTime - serviceCallTime}ms")
            println(" CONTROLLER: Service call completed, returning result")
            println("⏰ Controller end time: ${java.time.LocalDateTime.now()}")
            return result
        } catch (e: Exception) {
            val controllerTotalTime = System.currentTimeMillis() - controllerStartTime
            println("⏱️ [CONTROLLER] Total time before error: ${controllerTotalTime}ms")
            println(" CONTROLLER ERROR: ${e.message}")
            println(" Exception type: ${e.javaClass.simpleName}")
            e.printStackTrace()
            
            // 返回错误响应而不是抛出异常
            return MessageResponse(
                id = null,
                name = "Controller Error",
                code = "CONTROLLER_ERROR",
                type = "error",
                message = "Error in controller: ${e.message}",
                errorPosition = null
            )
        }
    }
    @PostMapping("/batchScan")
    fun batchScan(@Valid @RequestBody request: com.ffii.fpsms.modules.stock.web.model.BatchScanRequest): MessageResponse {
        return stockOutLineService.batchScan(request)
    }
}