package kr.co.accura.wbx.spring.approval;

import kr.co.accura.wbx.spring.common.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 통합 결재 API — WBX 패턴 이식
 * POST /api/approvals/unified/action/{type}/{id}/approve
 * POST /api/approvals/unified/action/{type}/{id}/reject
 */
@RestController
@RequestMapping("${wbx.spring.api-prefix:/api}/approvals/unified")
@RequiredArgsConstructor
public class UnifiedApprovalController {

    private final ApprovalHandlerRegistry registry;

    @PostMapping("/action/{type}/{id}/approve")
    public ApprovalResult approve(@PathVariable String type,
                                   @PathVariable Long id,
                                   @RequestBody(required = false) ActionRequest req) {
        return registry.get(type)
                .approve(id, SecurityUtils.getCurrentUserId(),
                        req != null ? req.comment() : null);
    }

    @PostMapping("/action/{type}/{id}/reject")
    public ApprovalResult reject(@PathVariable String type,
                                  @PathVariable Long id,
                                  @RequestBody ActionRequest req) {
        return registry.get(type)
                .reject(id, SecurityUtils.getCurrentUserId(), req.comment());
    }

    @GetMapping("/pending")
    public Map<String, Object> pending(@RequestParam(defaultValue = "0") int skip,
                                        @RequestParam(defaultValue = "20") int limit) {
        Long userId = SecurityUtils.getCurrentUserId();
        List<ApprovalPendingDto> all = registry.getAll().stream()
                .flatMap(h -> h.getPending(userId, PageRequest.of(0, 100)).getContent().stream())
                .sorted(Comparator.comparing(ApprovalPendingDto::submittedAt).reversed())
                .toList();

        int end = Math.min(skip + limit, all.size());
        return Map.of(
                "items", skip < all.size() ? all.subList(skip, end) : List.of(),
                "total", all.size()
        );
    }
}
