package com.ga.api.controller.commission;

import com.ga.api.service.commission.StatuteService;
import com.ga.common.annotation.DataChangeLog;
import com.ga.common.annotation.RequirePermission;
import com.ga.common.model.ApiResponse;
import com.ga.core.vo.commission.StatuteConfigResp;
import com.ga.core.vo.commission.StatuteConfigSaveReq;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "환수시효관리")
@RestController
@RequestMapping("/api/statute")
@RequiredArgsConstructor
public class StatuteController {

    private final StatuteService service;

    @GetMapping
    @RequirePermission(menu = "STATUTE_CONFIG", perm = "READ")
    public ApiResponse<List<StatuteConfigResp>> list() {
        return ApiResponse.ok(service.listConfigs());
    }

    @GetMapping("/{configId}")
    @RequirePermission(menu = "STATUTE_CONFIG", perm = "READ")
    public ApiResponse<StatuteConfigResp> detail(@PathVariable Long configId) {
        return ApiResponse.ok(service.detailConfig(configId));
    }

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

    @PutMapping("/{configId}")
    @RequirePermission(menu = "STATUTE_CONFIG", perm = "UPDATE")
    @DataChangeLog(menu = "STATUTE_CONFIG", table = "statute_config")
    public ApiResponse<Void> update(@PathVariable Long configId,
                                    @Valid @RequestBody StatuteConfigSaveReq req) {
        service.updateConfig(configId, req);
        return ApiResponse.ok();
    }

    /**
     * 만료 대상 환수채권 일괄 대손 처리.
     * Request body: { "baseMonth": "YYYYMM" }
     */
    @PostMapping("/expire")
    @RequirePermission(menu = "STATUTE_CONFIG", perm = "UPDATE")
    @DataChangeLog(menu = "STATUTE_CONFIG", table = "clawback_receivable")
    public ApiResponse<Integer> expire(@RequestBody Map<String, String> body) {
        String baseMonth = body.get("baseMonth");
        if (baseMonth == null || baseMonth.isBlank()) {
            baseMonth = com.ga.common.util.DateUtil.getSettleMonth();
        }
        return ApiResponse.ok(service.expireOverdue(baseMonth));
    }
}
