package com.ffii.fpsms.modules.report.web

import net.sf.jasperreports.engine.*
import org.springframework.http.*
import org.springframework.web.bind.annotation.*
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import com.ffii.fpsms.modules.report.service.StockItemConsumptionTrendReportService
import com.ffii.fpsms.modules.report.service.ReportService

@RestController
@RequestMapping("/report")
class StockItemConsumptionTrendReportController(
    private val stockItemConsumptionTrendReportService: StockItemConsumptionTrendReportService,
    private val reportService: ReportService,
) {

    @GetMapping("/print-stock-item-consumption-trend")
    fun generateStockItemConsumptionTrendReport(
        @RequestParam(required = false) stockCategory: String?,
        @RequestParam(required = false) itemCode: String?,
        @RequestParam(required = false) year: String?,
        @RequestParam(required = false) lastOutDateStart: String?,
        @RequestParam(required = false) lastOutDateEnd: String?
    ): ResponseEntity<ByteArray> {
        try {
            val parameters = mutableMapOf<String, Any>()
            
            // Set report header parameters
            parameters["stockCategory"] = stockCategory ?: "All"
            parameters["stockSubCategory"] = "All"
            parameters["itemNo"] = itemCode ?: "All"
            parameters["year"] = year ?: LocalDate.now().year.toString()
            parameters["reportDate"] = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            parameters["reportTime"] = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"))
            parameters["lastOutDateStart"] = lastOutDateStart ?: ""
            parameters["lastOutDateEnd"] = lastOutDateEnd ?: ""
            parameters["deliveryPeriodStart"] = ""
            parameters["deliveryPeriodEnd"] = ""

            // Query the DB to get a list of data
            val dbData = stockItemConsumptionTrendReportService.searchStockItemConsumptionTrendReport(
                stockCategory,
                itemCode,
                year,
                lastOutDateStart,
                lastOutDateEnd
            )

            val pdfBytes = reportService.createPdfResponse(
                "/jasper/StockItemConsumptionTrendReport.jrxml", 
                parameters, 
                dbData
            )

            val headers = HttpHeaders().apply {
                contentType = MediaType.APPLICATION_PDF
                setContentDispositionFormData("attachment", "StockItemConsumptionTrendReport.pdf")
                set("filename", "StockItemConsumptionTrendReport.pdf") 
            }

            return ResponseEntity(pdfBytes, headers, HttpStatus.OK)
        } catch (e: Exception) {
            e.printStackTrace()
            val errorMessage = e.message ?: "Unknown error occurred"
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(errorMessage.toByteArray())
        }
    }

    @GetMapping("/stock-item-code-prefixes")
    fun getStockItemCodePrefixes(
        @RequestParam(required = false) stockCategory: String?
    ): ResponseEntity<List<Map<String, String>>> {
        val prefixes = stockItemConsumptionTrendReportService.getStockItemCodePrefixes(stockCategory)
        return ResponseEntity(prefixes, HttpStatus.OK)
    }
}
