package com.ffii.fpsms.modules.logistic.web

import com.ffii.fpsms.modules.logistic.service.LogisticService
import com.ffii.fpsms.modules.logistic.web.models.DeleteLogisticRequest
import com.ffii.fpsms.modules.logistic.web.models.LogisticResponse
import com.ffii.fpsms.modules.logistic.web.models.SaveLogisticRequest
import com.ffii.fpsms.modules.logistic.web.models.SaveLogisticsBatchRequest
import com.ffii.fpsms.modules.master.web.models.MessageResponse
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/logistic")
class LogisticController(
    private val logisticService: LogisticService,
) {
    @GetMapping("/all")
    fun findAll(): List<LogisticResponse> {
        return logisticService.findAll().map { it.toResponse() }
    }

    @GetMapping("/{id}")
    fun findById(@PathVariable id: Long): LogisticResponse {
        return logisticService.requireById(id).toResponse()
    }

    @PostMapping("/save")
    fun save(@Valid @RequestBody request: SaveLogisticRequest): LogisticResponse {
        return logisticService.save(request).toResponse()
    }

    /** 批次新增主檔；單一 transaction，與 [save] 分開避免誤用 id 更新混進批次。 */
    @PostMapping("/save-batch")
    fun saveBatch(@Valid @RequestBody body: SaveLogisticsBatchRequest): List<LogisticResponse> {
        return logisticService.saveBatchCreate(body.items).map { it.toResponse() }
    }

    @PostMapping("/delete")
    fun delete(@Valid @RequestBody request: DeleteLogisticRequest): ResponseEntity<MessageResponse> {
        val result = logisticService.deleteById(request.id)
        return ResponseEntity.ok(
            MessageResponse(
                id = request.id,
                name = null,
                code = null,
                type = "logistic",
                message = result,
                errorPosition = null,
                entity = null,
            )
        )
    }

    private fun com.ffii.fpsms.modules.logistic.entity.Logistic.toResponse(): LogisticResponse {
        return LogisticResponse(
            id = this.id ?: 0L,
            logisticName = this.logisticName ?: "",
            carPlate = this.carPlate ?: "",
            driverName = this.driverName ?: "",
            driverNumber = this.driverNumber ?: 0,
        )
    }
}

