package com.ga.api.controller.commission;

import com.ga.api.service.commission.ClawbackInstallmentService;
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.commission.ClawbackInstallmentPlanResp;
import com.ga.core.vo.commission.ClawbackInstallmentPlanSearchParam;
import com.ga.core.vo.commission.ClawbackInstallmentPlanVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "환수분할상환")
@RestController
@RequestMapping("/api/clawback-installments")
@RequiredArgsConstructor
public class ClawbackInstallmentController {

    private final ClawbackInstallmentService service;

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

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

    @GetMapping("/by-receivable/{receivableId}")
    @RequirePermission(menu = "CLAWBACK_INSTALLMENT", perm = "READ")
    public ApiResponse<List<ClawbackInstallmentPlanVO>> listByReceivable(
            @PathVariable Long receivableId) {
        return ApiResponse.ok(service.listByReceivable(receivableId));
    }

    /**
     * 분할상환 계획 생성.
     * Request body: { "count": N, "baseMonth": "YYYYMM" }
     */
    @PostMapping("/generate/{receivableId}")
    @RequirePermission(menu = "CLAWBACK_INSTALLMENT", perm = "CREATE")
    @DataChangeLog(menu = "CLAWBACK_INSTALLMENT", table = "clawback_installment_plan")
    public ApiResponse<Void> generate(@PathVariable Long receivableId,
                                      @RequestBody Map<String, Object> body) {
        int count = Integer.parseInt(body.get("count").toString());
        String baseMonth = body.get("baseMonth").toString();
        service.generate(receivableId, count, baseMonth);
        return ApiResponse.ok();
    }

    @PostMapping("/{planId}/cancel")
    @RequirePermission(menu = "CLAWBACK_INSTALLMENT", perm = "UPDATE")
    @DataChangeLog(menu = "CLAWBACK_INSTALLMENT", table = "clawback_installment_plan")
    public ApiResponse<Void> cancel(@PathVariable Long planId) {
        service.cancel(planId);
        return ApiResponse.ok();
    }
}
