package com.zioinfo.mes.workorder;

import com.zioinfo.mes.common.ApiResponse;
import com.zioinfo.mes.common.AuthSupport;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 작업지시 API. 조회 Viewer+, 생성/수정 Worker+, RELEASE 이상 전이 Manager+.
 */
@RestController
@RequestMapping("/api/mes/workorders")
@RequiredArgsConstructor
public class WorkOrderController {

    private final WorkOrderService service;

    @GetMapping
    public ApiResponse<List<MesWorkOrder>> list(@RequestParam(required = false) String status,
                                                @RequestParam(required = false) String itemCode,
                                                @RequestParam(required = false) String keyword) {
        return ApiResponse.ok(service.list(status, itemCode, keyword));
    }

    @GetMapping("/kanban")
    public ApiResponse<List<Map<String, Object>>> kanban() {
        return ApiResponse.ok(service.kanbanCounts());
    }

    @GetMapping("/{id}")
    public ApiResponse<MesWorkOrder> get(@PathVariable Long id) {
        return ApiResponse.ok(service.get(id));
    }

    @PostMapping
    public ApiResponse<MesWorkOrder> create(@RequestBody MesWorkOrder wo, Authentication auth) {
        return ApiResponse.ok(service.create(wo, AuthSupport.actor(auth)));
    }

    @PutMapping("/{id}")
    public ApiResponse<MesWorkOrder> update(@PathVariable Long id, @RequestBody MesWorkOrder wo, Authentication auth) {
        return ApiResponse.ok(service.update(id, wo, AuthSupport.actor(auth)));
    }

    /** 상태 전이 — action: RELEASE/START/COMPLETE/CLOSE/CANCEL. RELEASE/CLOSE/CANCEL 은 Manager+. */
    @PostMapping("/{id}/transition")
    public ApiResponse<MesWorkOrder> transition(@PathVariable Long id, @RequestBody TransitionRequest req, Authentication auth) {
        String a = req.action() == null ? "" : req.action().toUpperCase();
        if (a.equals("RELEASE") || a.equals("CLOSE") || a.equals("CANCEL")) {
            AuthSupport.requireManager(auth);
        }
        return ApiResponse.ok(service.transition(id, req.action(), AuthSupport.actor(auth)));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id, Authentication auth) {
        AuthSupport.requireManager(auth);
        service.delete(id);
        return ApiResponse.ok(null);
    }

    record TransitionRequest(String action) {}
}
