package click.kamil.enterprise.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/machine")
public class StateMachineController {

    private final StateMachineDispatcher dispatcher;

    @Autowired
    public StateMachineController(StateMachineDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @PostMapping("/order/pay")
    public ResponseEntity<String> payOrder(@RequestParam(defaultValue = "system-user") String userId) {
        return ResponseEntity.ok(dispatcher.payOrder(userId));
    }

    @PostMapping("/order/ship")
    public ResponseEntity<String> shipOrder(@RequestParam(defaultValue = "system-user") String userId) {
        return ResponseEntity.ok(dispatcher.shipOrder(userId));
    }

    @PostMapping("/document/submit")
    public ResponseEntity<String> submitDocument(@RequestParam(defaultValue = "system-user") String userId) {
        return ResponseEntity.ok(dispatcher.submitDocument(userId));
    }

    @PostMapping("/document/approve")
    public ResponseEntity<String> approveDocument(@RequestParam(defaultValue = "system-user") String userId) {
        return ResponseEntity.ok(dispatcher.approveDocument(userId));
    }

    @PostMapping("/document/reject")
    public ResponseEntity<String> rejectDocument(@RequestParam(defaultValue = "system-user") String userId) {
        return ResponseEntity.ok(dispatcher.rejectDocument(userId));
    }

    @PostMapping("/user/verify")
    public ResponseEntity<String> verifyUser(@RequestParam(defaultValue = "system-user") String userId) {
        return ResponseEntity.ok(dispatcher.verifyUser(userId));
    }

    @PostMapping("/user/suspend")
    public ResponseEntity<String> suspendUser(@RequestParam(defaultValue = "system-user") String userId) {
        return ResponseEntity.ok(dispatcher.suspendUser(userId));
    }

    @PostMapping("/{machineType}/transition/{event}")
    public ResponseEntity<String> transition(
            @PathVariable String machineType,
            @PathVariable String event,
            @RequestParam(defaultValue = "system-user") String userId) {
        try {
            String result = dispatcher.dispatch(machineType, event);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}
