package com.ffii.fpsms.py

import com.ffii.fpsms.modules.jobOrder.entity.JobOrder
import com.ffii.fpsms.modules.jobOrder.entity.JobOrderRepository
import org.springframework.format.annotation.DateTimeFormat
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.time.LocalDate
import java.time.LocalDateTime

/**
 * Public API for Python clients. No login required.
 * Base path: /py
 */
@RestController
@RequestMapping("/py")
open class PyController(
    private val jobOrderRepository: JobOrderRepository,
) {

    /**
     * List job orders by planStart date.
     * GET /py/job-orders?planStart=yyyy-MM-dd
     * @param planStart Date to filter by (default: today). Format: yyyy-MM-dd
     * @return List of job orders with id, code, planStart, itemCode, itemName, reqQty
     */
    @GetMapping("/job-orders")
    open fun listJobOrders(
        @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) planStart: LocalDate?,
    ): ResponseEntity<List<PyJobOrderListItem>> {
        val date = planStart ?: LocalDate.now()
        val dayStart = date.atStartOfDay()
        val dayEndExclusive = date.plusDays(1).atStartOfDay()
        val orders = jobOrderRepository.findByDeletedFalseAndPlanStartFromBeforeExclusiveOrderByIdAsc(dayStart, dayEndExclusive)
        val list = orders.map { jo -> toListItem(jo) }
        return ResponseEntity.ok(list)
    }

    private fun toListItem(jo: JobOrder): PyJobOrderListItem {
        val itemCode = jo.bom?.item?.code ?: jo.bom?.code
        val itemName = jo.bom?.name ?: jo.bom?.item?.name
        return PyJobOrderListItem(
            id = jo.id!!,
            code = jo.code,
            planStart = jo.planStart,
            itemCode = itemCode,
            itemName = itemName,
            reqQty = jo.reqQty,
        )
    }
}
