package com.ffii.fpsms.modules.common.internalSetup

import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/setup")
class SetupController(
    private val userSetup: UserSetup,
    private val warehouseSetup: WarehouseSetup,
    private val itemsSetup: ItemsSetup,
    private val inventorySetup: InventorySetup
) {

    @PostMapping("/user")
    fun importUsersFromExcel(@RequestBody request: Map<String, String>): ResponseEntity<Map<String, Any>> {
        val filePath = request["filePath"]

        if (filePath == null || filePath.isEmpty()) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to "filePath is required"
            )
            return ResponseEntity.badRequest().body(errorResponse)
        }

        try {
            val createdCount = userSetup.importExcelFromLocal(filePath)
            val response = mapOf(
                "success" to true,
                "message" to "Users imported successfully",
                "createdCount" to createdCount
            )
            return ResponseEntity.ok(response)
        } catch (e: Exception) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to (e.message ?: "Unknown error occurred")
            )
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse)
        }
    }

    @PostMapping("/warehouse")
    fun importWarehousesFromExcel(@RequestBody request: Map<String, String>): ResponseEntity<Map<String, Any>> {
        val filePath = request["filePath"]

        if (filePath == null || filePath.isEmpty()) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to "filePath is required"
            )
            return ResponseEntity.badRequest().body(errorResponse)
        }

        try {
            val createdCount = warehouseSetup.importExcelFromLocal(filePath)
            val response = mapOf(
                "success" to true,
                "message" to "Warehouses imported successfully",
                "createdCount" to createdCount
            )
            return ResponseEntity.ok(response)
        } catch (e: Exception) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to (e.message ?: "Unknown error occurred")
            )
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse)
        }
    }

    @PostMapping("/item")
    fun importItemsFromExcel(@RequestBody request: Map<String, String>): ResponseEntity<Map<String, Any>> {
        val filePath = request["filePath"]

        if (filePath == null || filePath.isEmpty()) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to "filePath is required"
            )
            return ResponseEntity.badRequest().body(errorResponse)
        }

        try {
            val updatedCount = itemsSetup.importExcelFromLocal(filePath)
            val response = mapOf(
                "success" to true,
                "message" to "Items imported successfully",
                "updatedCount" to updatedCount
            )
            return ResponseEntity.ok(response)
        } catch (e: Exception) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to (e.message ?: "Unknown error occurred")
            )
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse)
        }
    }

    @PostMapping("/inventory")
    fun importInventoryFromExcel(@RequestBody request: Map<String, String>): ResponseEntity<Map<String, Any>> {
        val filePath = request["filePath"]

        if (filePath == null || filePath.isEmpty()) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to "filePath is required"
            )
            return ResponseEntity.badRequest().body(errorResponse)
        }

        try {
            val createdCount = inventorySetup.importExcelFromLocal(filePath)
            val response = mapOf(
                "success" to true,
                "message" to "Inventory stock in created successfully",
                "createdCount" to createdCount
            )
            return ResponseEntity.ok(response)
        } catch (e: Exception) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to (e.message ?: "Unknown error occurred")
            )
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse)
        }
    }

    @PostMapping("/inventory/print-all-lot-stockin-labels")
    fun printAllLotStockInLabels(@RequestBody request: Map<String, Any>): ResponseEntity<Map<String, Any>> {
        val printerId = (request["printerId"] as? Number)?.toLong()
        val printQty = (request["printQty"] as? Number)?.toInt() ?: 1
        val fromIndex = (request["fromIndex"] as? Number)?.toInt()
        val toIndex = (request["toIndex"] as? Number)?.toInt()

        if (printerId == null) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to "printerId is required"
            )
            return ResponseEntity.badRequest().body(errorResponse)
        }

        // Validate range if provided
        if (fromIndex != null && toIndex != null) {
            if (fromIndex < 0 || toIndex < 0) {
                val errorResponse = mapOf(
                    "success" to false,
                    "error" to "fromIndex and toIndex must be >= 0"
                )
                return ResponseEntity.badRequest().body(errorResponse)
            }
            if (fromIndex > toIndex) {
                val errorResponse = mapOf(
                    "success" to false,
                    "error" to "fromIndex must be <= toIndex"
                )
                return ResponseEntity.badRequest().body(errorResponse)
            }
        }

        try {
            val printedCount = inventorySetup.printAllLotStockInLabels(
                printerId = printerId,
                printQty = printQty,
                fromIndex = fromIndex,
                toIndex = toIndex
            )
            val response = mapOf(
                "success" to true,
                "message" to "Lot stock-in labels printed successfully",
                "printedCount" to printedCount
            )
            return ResponseEntity.ok(response)
        } catch (e: Exception) {
            val errorResponse = mapOf(
                "success" to false,
                "error" to (e.message ?: "Unknown error occurred")
            )
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse)
        }
    }

    @PostMapping("/inventory/print-lot-stockin-labels-by-item-ids")
    fun printLotStockInLabelsByItemIds(@RequestBody request: Map<String, Any>): ResponseEntity<Map<String, Any>> {
        val printerId = (request["printerId"] as? Number)?.toLong()
        val printQty = (request["printQty"] as? Number)?.toInt() ?: 1
        val fromIndex = (request["fromIndex"] as? Number)?.toInt()
        val toIndex = (request["toIndex"] as? Number)?.toInt()
        val itemIds = (request["itemIds"] as? List<*>)?.mapNotNull { (it as? Number)?.toLong() } ?: emptyList()

        if (printerId == null) return ResponseEntity.badRequest().body(mapOf("success" to false, "error" to "printerId is required"))
        if (itemIds.isEmpty()) return ResponseEntity.badRequest().body(mapOf("success" to false, "error" to "itemIds is required"))

        val printedCount = inventorySetup.printLotStockInLabelsByItemIds(
            printerId = printerId,
            itemIds = itemIds,
            printQty = printQty,
            fromIndex = fromIndex,
            toIndex = toIndex
        )
        return ResponseEntity.ok(mapOf("success" to true, "message" to "Lot stock-in labels printed successfully", "printedCount" to printedCount))
    }
    data class PrintProgressResult(
        val success: Boolean,
        val lastIndex: Int,
        val totalLots: Int,
        val errorMessage: String? = null
    )
    @PostMapping("/inventory/print-lot-stockin-labels-by-item-ids-v2")
    fun printLotStockInLabelsByItemIdsV2(@RequestBody request: Map<String, Any>): ResponseEntity<Map<String, Any>> {
        val printerId = (request["printerId"] as? Number)?.toLong()
        val printQty = (request["printQty"] as? Number)?.toInt() ?: 1
        val fromIndex = (request["fromIndex"] as? Number)?.toInt()
        val toIndex = (request["toIndex"] as? Number)?.toInt()
        val itemIds = (request["itemIds"] as? List<*>)?.mapNotNull { (it as? Number)?.toLong() } ?: emptyList()
    
        if (printerId == null) {
            return ResponseEntity.badRequest().body(
                mapOf(
                    "success" to false,
                    "message" to "printerId is required"
                )
            )
        }
        if (itemIds.isEmpty()) {
            return ResponseEntity.badRequest().body(
                mapOf(
                    "success" to false,
                    "message" to "itemIds is required"
                )
            )
        }
    
        return try {
            val result = inventorySetup.printLotStockInLabelsByItemIdsV2(
                printerId = printerId,
                itemIds = itemIds,
                printQty = printQty,
                fromIndex = fromIndex,
                toIndex = toIndex
            )
    
            val body = if (result.success) {
                mapOf(
                    "success" to true,
                    "message" to "Lot stock-in labels printed successfully",
                    "lastIndex" to result.lastIndex,
                    "totalLots" to result.totalLots
                )
            } else {
                mapOf(
                    "success" to false,
                    "message" to (result.errorMessage ?: "Printer error"),
                    "lastIndex" to result.lastIndex,
                    "totalLots" to result.totalLots
                )
            }
    
            ResponseEntity.ok(body)
        } catch (e: Exception) {
            e.printStackTrace()
            ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                mapOf(
                    "success" to false,
                    "message" to (e.message ?: "Unknown error occurred while printing lot stock-in labels")
                )
            )
        }
    }
    @PostMapping("/inventory/print-lot-stockin-labels-by-store-ids")
fun printLotStockInLabelsByStoreIds(
    @RequestBody request: Map<String, Any>
): ResponseEntity<Map<String, Any>> {

    val printerId = (request["printerId"] as? Number)?.toLong()
    val printQty = (request["printQty"] as? Number)?.toInt() ?: 1
    val fromIndex = (request["fromIndex"] as? Number)?.toInt()
    val toIndex = (request["toIndex"] as? Number)?.toInt()
    // storeIds: ["2F","4F"]
    val storeIds = (request["storeIds"] as? List<*>)?.mapNotNull { it?.toString() } ?: emptyList()

    if (printerId == null) {
        return ResponseEntity.badRequest().body(
            mapOf(
                "success" to false,
                "message" to "printerId is required"
            )
        )
    }
    if (storeIds.isEmpty()) {
        return ResponseEntity.badRequest().body(
            mapOf(
                "success" to false,
                "message" to "storeIds is required"
            )
        )
    }

    return try {
        val result = inventorySetup.printLotStockInLabelsByStoreIdsV1(
            printerId = printerId,
            storeIds = storeIds,
            printQty = printQty,
            fromIndex = fromIndex,
            toIndex = toIndex
        )

        val body =
            if (result.success) {
                mapOf(
                    "success" to true,
                    "message" to "Lot stock-in labels printed successfully",
                    "lastIndex" to result.lastIndex,
                    "totalLots" to result.totalLots
                )
            } else {
                mapOf(
                    "success" to false,
                    "message" to (result.errorMessage ?: "Printer error"),
                    "lastIndex" to result.lastIndex,
                    "totalLots" to result.totalLots
                )
            }

        ResponseEntity.ok(body)
    } catch (e: Exception) {
        ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
            mapOf(
                "success" to false,
                "message" to (e.message ?: "Unknown error occurred while printing lot stock-in labels")
            )
        )
    }
}
}