package com.ga.api.controller.settle;

import com.ga.api.service.settle.SettleCorrectionService;
import com.ga.common.annotation.DataChangeLog;
import com.ga.common.annotation.RequirePermission;
import com.ga.common.model.ApiResponse;
import com.ga.common.model.PageResponse;
import com.ga.core.vo.settle.SettleCorrectionResp;
import com.ga.core.vo.settle.SettleCorrectionSaveReq;
import com.ga.core.vo.settle.SettleCorrectionSearchParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "정산 정정 관리")
@RestController
@RequestMapping("/api/settle-corrections")
@RequiredArgsConstructor
public class SettleCorrectionController {

    private final SettleCorrectionService service;

    @GetMapping
    @RequirePermission(menu = "SETTLE_CORRECTION", perm = "READ")
    public ApiResponse<PageResponse<SettleCorrectionResp>> list(@ModelAttribute SettleCorrectionSearchParam param) {
        return ApiResponse.ok(service.list(param));
    }

    @GetMapping("/{correctionId}")
    @RequirePermission(menu = "SETTLE_CORRECTION", perm = "READ")
    public ApiResponse<SettleCorrectionResp> detail(@PathVariable Long correctionId) {
        return ApiResponse.ok(service.detail(correctionId));
    }

    @GetMapping("/by-settle/{originalSettleId}")
    @RequirePermission(menu = "SETTLE_CORRECTION", perm = "READ")
    public ApiResponse<List<SettleCorrectionResp>> listByOriginalSettle(@PathVariable Long originalSettleId) {
        return ApiResponse.ok(service.listByOriginalSettle(originalSettleId));
    }

    @PostMapping
    @RequirePermission(menu = "SETTLE_CORRECTION", perm = "CREATE")
    @DataChangeLog(menu = "SETTLE_CORRECTION", table = "settle_correction")
    public ApiResponse<Long> create(@Valid @RequestBody SettleCorrectionSaveReq req) {
        return ApiResponse.ok(service.create(req));
    }

    @PostMapping("/{correctionId}/approve")
    @RequirePermission(menu = "SETTLE_CORRECTION", perm = "APPROVE")
    @DataChangeLog(menu = "SETTLE_CORRECTION", table = "settle_correction")
    public ApiResponse<Void> approve(@PathVariable Long correctionId) {
        service.approve(correctionId);
        return ApiResponse.ok();
    }

    @PostMapping("/{correctionId}/cancel")
    @RequirePermission(menu = "SETTLE_CORRECTION", perm = "UPDATE")
    @DataChangeLog(menu = "SETTLE_CORRECTION", table = "settle_correction")
    public ApiResponse<Void> cancel(@PathVariable Long correctionId, @RequestBody Map<String, String> body) {
        service.cancel(correctionId, body.get("cancelReason"));
        return ApiResponse.ok();
    }
}
