package com.ffii.fpsms.modules.pickOrder.web

import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.pickOrder.service.TruckLaneVersionService
import com.ffii.fpsms.modules.pickOrder.web.models.CreateTruckLaneSnapshotRequest
import com.ffii.fpsms.modules.pickOrder.web.models.TruckLaneVersionDiffResponse
import com.ffii.fpsms.modules.pickOrder.web.models.TruckLaneVersionLineResponse
import com.ffii.fpsms.modules.pickOrder.web.models.TruckLaneVersionResponse
import com.ffii.fpsms.modules.pickOrder.web.models.UpdateTruckLaneVersionNoteRequest
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/truckLaneVersion")
class TruckLaneVersionController(
    private val truckLaneVersionService: TruckLaneVersionService,
) {
    @PostMapping("/snapshot")
    fun createSnapshot(@Valid @RequestBody request: CreateTruckLaneSnapshotRequest): TruckLaneVersionResponse {
        return truckLaneVersionService.createSnapshot(request)
    }

    @GetMapping
    fun listVersions(
        @RequestParam(required = false) truckLanceCode: String?,
    ): List<TruckLaneVersionResponse> {
        val lane = truckLanceCode?.trim()?.takeIf { it.isNotEmpty() }
        return if (lane != null) {
            truckLaneVersionService.listVersionsByLane(lane)
        } else {
            truckLaneVersionService.listAllVersions()
        }
    }

    @GetMapping("/{versionId}/lines")
    fun getLines(@PathVariable versionId: Long): List<TruckLaneVersionLineResponse> {
        return truckLaneVersionService.getVersionLines(versionId)
    }

    @PatchMapping("/{versionId}/note")
    fun updateNote(
        @PathVariable versionId: Long,
        @Valid @RequestBody request: UpdateTruckLaneVersionNoteRequest,
    ): TruckLaneVersionResponse {
        return truckLaneVersionService.updateNote(versionId, request.note)
    }

    @GetMapping("/diff")
    fun diff(
        @RequestParam fromVersionId: Long,
        @RequestParam toVersionId: Long,
    ): TruckLaneVersionDiffResponse {
        return truckLaneVersionService.diff(fromVersionId, toVersionId)
    }

    @PostMapping("/{versionId}/restore")
    fun restore(@PathVariable versionId: Long): ResponseEntity<MessageResponse> {
        val msg = truckLaneVersionService.restore(versionId)
        return ResponseEntity.ok(
            MessageResponse(
                id = null,
                name = null,
                code = null,
                type = "OK",
                message = msg,
                errorPosition = null,
                entity = null,
            )
        )
    }
}

