package com.ga.api.controller.settle;

import com.ga.api.service.settle.ChargebackService;
import com.ga.api.service.settle.ChargebackUploadService;
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.ChargebackResp;
import com.ga.core.vo.settle.ChargebackSearchParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "환수자료 관리")
@Validated
@RestController
@RequestMapping("/api/chargebacks")
@RequiredArgsConstructor
public class ChargebackController {

    private final ChargebackService chargebackService;
    private final ChargebackUploadService chargebackUploadService;

    @Operation(summary = "환수자료 목록 조회")
    @GetMapping
    @RequirePermission(menu = "CHARGEBACK_DATA", perm = "READ")
    public ApiResponse<PageResponse<ChargebackResp>> list(@ModelAttribute ChargebackSearchParam param) {
        return ApiResponse.ok(chargebackService.list(param));
    }

    @Operation(summary = "환수자료 엑셀 다운로드")
    @GetMapping("/export")
    @RequirePermission(menu = "CHARGEBACK_DATA", perm = "EXPORT")
    public void export(@ModelAttribute ChargebackSearchParam param, HttpServletResponse response) {
        chargebackService.export(param, response);
    }

    @Operation(summary = "보험사 환수자료 업로드",
               description = "정산월(YYYYMM) + 엑셀 파일(증권번호/환수금액/실효월/환수율). " +
                             "미존재 증권번호·cbAmount 오류는 에러행으로 반환. 동일 계약+정산월 중복은 스킵.")
    @PostMapping("/upload")
    @RequirePermission(menu = "CHARGEBACK_DATA", perm = "CREATE")
    @DataChangeLog(menu = "CHARGEBACK_DATA", table = "chargeback")
    public ApiResponse<ChargebackUploadService.UploadResult> upload(
            @Pattern(regexp = "\\d{6}", message = "settleMonth는 YYYYMM 형식이어야 합니다")
            @RequestParam String settleMonth,
            @RequestParam("file") MultipartFile file) {
        return ApiResponse.ok(chargebackUploadService.upload(settleMonth, file));
    }
}
