package com.ffii.fpsms.modules.master.web

import com.ffii.core.exception.NotFoundException
import com.ffii.core.response.RecordsRes
import com.ffii.core.utils.CriteriaArgsBuilder
import com.ffii.core.utils.PagingUtils
import com.ffii.fpsms.modules.master.entity.Items
import com.ffii.fpsms.modules.master.service.ItemsService
import com.ffii.fpsms.modules.master.web.models.ItemWithQcResponse
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.master.web.models.NewItemRequest
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.Valid
import org.springframework.web.bind.annotation.*
import java.util.Collections.emptyList

@RestController
@RequestMapping("/items")
class ItemsController(
    private val itemsService: ItemsService
) {
    @GetMapping
    fun allItems(): List<Items> {
        return itemsService.allItems()
    }

//    @GetMapping("/getRecordByPage")
//    fun getAllItemsByPage(@RequestBody filterRequest: HttpServletRequest): RecordsRes<Map<String, Any>> {
//        val pageSize = filterRequest.getParameter("pageSize").toString().toInt(); // Default to 10 if not provided
//        val pageNumber = filterRequest.getParameter("pageNum").toString().toInt(); // Default to 0 if not provided
//        val criteriaArgs = CriteriaArgsBuilder.withRequest(filterRequest)
//            .addStringLike("name")
//            .build();
//
//        val fullList = itemsService.getItemsByPage(criteriaArgs)?.subList(pageSize*pageNumber+1, pageSize*pageNumber+pageSize)
//        val outputList = fullList?.subList(pageSize*pageNumber+1, pageSize*pageNumber+pageSize)
//
//        return RecordsRes(outputList as List<Map<String, Any>>?, fullList?.size)
//    }

    @GetMapping("/getRecordByPage")
    fun getAllItemsByPage(
        request: HttpServletRequest
    ): RecordsRes<Map<String, Any>> {
        val criteriaArgs = CriteriaArgsBuilder.withRequest(request)
            .addStringLike("name")
            .addStringLike("code")
            .build()

        val pageSize = request.getParameter("pageSize")?.toIntOrNull() ?: 10 // Default to 10 if not provided
        val pageNum = request.getParameter("pageNum")?.toIntOrNull() ?: 1 // Default to 1 if not provided

        val fullList = itemsService.getItemsByPage(criteriaArgs) ?: emptyList()

        val paginatedList = PagingUtils.getPaginatedList(fullList,pageSize, pageNum)

        return RecordsRes(paginatedList as List<Map<String, Any>>, fullList.size)
    }

    @GetMapping("/details/{id}")
    fun getItems(@PathVariable id: Long): ItemWithQcResponse {
        return itemsService.getItem(id)
    }

    @PostMapping("/new")
    fun saveItem(@Valid @RequestBody newItem: NewItemRequest): MessageResponse {
        println("`````TESTING`````")
        return itemsService.saveItem(newItem)
    }
}