package com.ffii.fpsms.modules.report.web
import org.springframework.web.bind.annotation.*
import org.springframework.http.*
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import com.ffii.fpsms.modules.report.service.StockLedgerReportService
import com.ffii.fpsms.modules.report.service.ReportService

@RestController
@RequestMapping("/report")
class StockLedgerReportController(
    private val reportService: ReportService,
    private val stockLedgerReportService: StockLedgerReportService,
) {

    @GetMapping("/print-stock-ledger")
fun generateStockLedgerReport(
    @RequestParam(required = false) stockCategory: String?,
    @RequestParam(required = false) itemCode: String?,
    @RequestParam(required = false) storeLocation: String?,
    // URL 參數名仍然是 lastInDateStart / lastInDateEnd
    @RequestParam(name = "lastInDateStart", required = false) reportPeriodStart: String?,
    @RequestParam(name = "lastInDateEnd", required = false) reportPeriodEnd: String?,
): ResponseEntity<ByteArray> {
    val parameters = mutableMapOf<String, Any>()

    parameters["stockCategory"] = stockCategory ?: "All"
    parameters["stockSubCategory"] = stockCategory ?: "All"
    parameters["itemNo"] = itemCode ?: "All"
    parameters["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["storeLocation"] = storeLocation ?: ""
    parameters["balanceFilterStart"] = ""
    parameters["balanceFilterEnd"] = ""
    parameters["reportPeriodStart"] = reportPeriodStart ?: ""
    parameters["reportPeriodEnd"] = reportPeriodEnd ?: ""


    val dbData = stockLedgerReportService.searchStockLedgerReport(
        stockCategory = stockCategory,
        itemCode = itemCode,
        storeLocation = storeLocation,
        reportPeriodStart = reportPeriodStart,
        reportPeriodEnd = reportPeriodEnd,
    )

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

    val headers = HttpHeaders().apply {
        contentType = MediaType.APPLICATION_PDF
        setContentDispositionFormData("attachment", "StockLedgerReport.pdf")
        set("filename", "StockLedgerReport.pdf")
    }
    return ResponseEntity(pdfBytes, headers, HttpStatus.OK)
}
}