package com.ffii.fpsms.modules.pickOrder.web

import com.ffii.fpsms.modules.master.entity.projections.ShopAndTruck
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.pickOrder.entity.Truck
import org.springframework.web.bind.ServletRequestBindingException
import jakarta.servlet.http.HttpServletRequest
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartHttpServletRequest

import com.ffii.fpsms.modules.pickOrder.web.models.SaveTruckRequest
import com.ffii.fpsms.modules.pickOrder.web.models.CreateTruckWithoutShopRequest
import com.ffii.fpsms.modules.pickOrder.web.models.UpdateTruckShopDetailsRequest
import com.ffii.fpsms.modules.pickOrder.service.TruckService
import com.ffii.fpsms.modules.pickOrder.entity.TruckRepository
import com.ffii.fpsms.modules.pickOrder.web.models.SaveTruckLane
import com.ffii.fpsms.modules.pickOrder.web.models.deleteTruckLane
import jakarta.validation.Valid

@RestController
@RequestMapping("/truck")
class TruckController(
    private val truckService: TruckService,
    private val truckRepository: TruckRepository,
) {

    
    @PostMapping("/save")
    fun saveTruck(@RequestBody request: SaveTruckRequest): MessageResponse {
        try {
            val truck = truckService.saveTruck(request)
            return MessageResponse(
                id = truck.id,
                name = truck.shopName,
                code = truck.truckLanceCode,
                type = "truck",
                message = if (truck.id != null) "Truck updated successfully" else "Truck created successfully",
                errorPosition = null,
                entity = truck
            )
        } catch (e: Exception) {
            return MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "truck",
                message = "Error: ${e.message}",
                errorPosition = null,
                entity = null
            )
        }
    }

    @PostMapping("/createTruckInShop")
    fun createTruckInShop(@Valid @RequestBody request: SaveTruckRequest): MessageResponse {
        try {
            val truck = truckService.createTruckInShop(request)
            return MessageResponse(
                id = truck.id,
                name = truck.shopName,
                code = truck.truckLanceCode,
                type = "truck",
                message = "Truck created successfully",
                errorPosition = null,
                entity = truck
            )
        } catch (e: Exception) {
            return MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "truck",
                message = "Error: ${e.message}",
                errorPosition = null,
                entity = null
            )
        }
    }

    @PostMapping("/importExcel")
    @Throws(ServletRequestBindingException::class)
    fun importExcel(request: HttpServletRequest): ResponseEntity<*> {
        var workbook: Workbook? = null

        try {
            val multipartFile = (request as MultipartHttpServletRequest).getFile("multipartFileList")
            workbook = XSSFWorkbook(multipartFile?.inputStream)
        } catch (e: Exception) {
            println("Error reading Excel file: ${e.message}")
            return ResponseEntity.badRequest().body(
                MessageResponse(
                    id = null,
                    name = null,
                    code = null,
                    type = "truck",
                    message = "Error reading Excel file: ${e.message}",
                    errorPosition = null,
                    entity = null
                )
            )
        }

        val result = truckService.importExcel(workbook)
        return ResponseEntity.ok(
            MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "truck",
                message = result,
                errorPosition = null,
                entity = null
            )
        )
    }

    @GetMapping("/findTruckLane/{shopId}")
    fun findAllByShopId(@PathVariable shopId: Long): List<Truck> {
        return truckService.findAllByShopId(shopId);
    }

    @PostMapping("/updateTruckLane")
    fun updateTruckLane(@Valid @RequestBody request: SaveTruckLane): MessageResponse {
        try {
            val trucks = truckService.updateTruckLaneByTruckLanceCode(
                request
            )
            val truck = trucks.firstOrNull()
            return MessageResponse(
                id = truck?.id,
                name = truck?.shopName,
                code = truck?.truckLanceCode,
                type = "truck",
                message = if (truck != null) "Truck lane updated successfully" else "Truck lane not found",
                errorPosition = null,
                entity = truck
            )
        } catch (e: Exception) {
            return MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "truck",
                message = "Error: ${e.message}",
                errorPosition = null,
                entity = null
            )
        }
    }

    @PostMapping("/deleteTruckLane")
    fun deleteTruckLane(@Valid @RequestBody request: deleteTruckLane): MessageResponse {
        try {
            val result = truckService.deleteById(request.id)
            return MessageResponse(
                id = request.id,
                name = null,
                code = null,
                type = "truck",
                message = result,
                errorPosition = null,
                entity = null
            )
        } catch (e: Exception) {
            return MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "truck",
                message = "Error: ${e.message}",
                errorPosition = null,
                entity = null
            )
        }
    }

    @GetMapping("/findAllUniqueTruckLanceCodeAndRemarkCombinations")
    fun findAllUniqueTruckLanceCodeAndRemarkCombinations(): List<Truck> {
        return truckService.findAllUniqueTruckLanceCodeAndRemarkCombinations()
    }


    @GetMapping("/findAllFromShopAndTruckByTruckLanceCodeAndDeletedFalse")
    fun findAllFromShopAndTruckByTruckLanceCodeAndDeletedFalse(@RequestParam truckLanceCode: String): List<ShopAndTruck> {
        return truckService.findAllFromShopAndTruckByTruckLanceCodeAndDeletedFalse(truckLanceCode)
    }

    @GetMapping("/findAllByTruckLanceCodeAndDeletedFalse")
    fun findAllByTruckLanceCodeAndDeletedFalse(@RequestParam truckLanceCode: String): List<Truck> {
        return truckService.findAllByTruckLanceCodeAndDeletedFalse(truckLanceCode)
    }

    @GetMapping("/findAllUniqueShopNamesAndCodesFromTrucks")
    fun findAllUniqueShopNamesAndCodesFromTrucks(): List<Map<String, String>> {
        return truckService.findAllUniqueShopNamesAndCodesFromTrucks()
    }

    @GetMapping("/findAllUniqueRemarksFromTrucks")
    fun findAllUniqueRemarksFromTrucks(): List<String> {
        return truckService.findAllUniqueRemarksFromTrucks()
    }

    @GetMapping("/findAllUniqueShopCodesFromTrucks")
    fun findAllUniqueShopCodesFromTrucks(): List<String> {
        return truckService.findAllUniqueShopCodesFromTrucks()
    }

    @GetMapping("/findAllUniqueShopNamesFromTrucks")
    fun findAllUniqueShopNamesFromTrucks(): List<String> {
        return truckService.findAllUniqueShopNamesFromTrucks()
    }

    @PostMapping("/updateTruckShopDetails")
    fun updateTruckShopDetails(@Valid @RequestBody request: UpdateTruckShopDetailsRequest): MessageResponse {
        try {
            val truck = truckService.updateTruckShopDetails(request)
            return MessageResponse(
                id = truck.id,
                name = truck.shopName,
                code = truck.truckLanceCode,
                type = "truck",
                message = "Truck shop details updated successfully",
                errorPosition = null,
                entity = truck
            )
        } catch (e: Exception) {
            return MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "truck",
                message = "Error: ${e.message}",
                errorPosition = null,
                entity = null
            )
        }
    }

    @PostMapping("/createTruckWithoutShop")
    fun createTruckWithoutShop(@Valid @RequestBody request: CreateTruckWithoutShopRequest): MessageResponse {
        try {
            val truck = truckService.createTruckWithoutShop(request)
            return MessageResponse(
                id = truck.id,
                name = truck.shopName,
                code = truck.truckLanceCode,
                type = "truck",
                message = "Truck created successfully",
                errorPosition = null,
                entity = truck
            )
        } catch (e: Exception) {
            return MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "truck",
                message = "Error: ${e.message}",
                errorPosition = null,
                entity = null
            )
        }
    }

}
