package com.ga.api.controller.commission;

import com.ga.api.service.commission.IncomeCommissionService;
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.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@Tag(name = "수입수수료/수지차")
@RestController
@RequestMapping("/api/income-commissions")
@RequiredArgsConstructor
public class IncomeCommissionController {

    private final IncomeCommissionService service;

    // ── Income Ledger ────────────────────────────────────────────────────────

    @GetMapping("/ledgers")
    @RequirePermission(menu = "INCOME_COMM", perm = "READ")
    public ApiResponse<PageResponse<IncomeCommissionLedgerResp>> listLedgers(
            @ModelAttribute IncomeCommissionLedgerSearchParam param) {
        return ApiResponse.ok(service.listLedgers(param));
    }

    @GetMapping("/ledgers/{incomeId}")
    @RequirePermission(menu = "INCOME_COMM", perm = "READ")
    public ApiResponse<IncomeCommissionLedgerResp> detailLedger(@PathVariable Long incomeId) {
        return ApiResponse.ok(service.detailLedger(incomeId));
    }

    @PostMapping("/ledgers")
    @RequirePermission(menu = "INCOME_COMM", perm = "CREATE")
    @DataChangeLog(menu = "INCOME_COMM", table = "income_commission_ledger")
    public ApiResponse<Long> createLedger(@Valid @RequestBody IncomeCommissionLedgerSaveReq req) {
        return ApiResponse.ok(service.createLedger(req));
    }

    // ── Margin Summary ───────────────────────────────────────────────────────

    @GetMapping("/margins")
    @RequirePermission(menu = "INCOME_COMM", perm = "READ")
    public ApiResponse<PageResponse<MarginSummaryResp>> listMargins(
            @ModelAttribute MarginSummarySearchParam param) {
        return ApiResponse.ok(service.listMargins(param));
    }

    @GetMapping("/margins/{marginId}")
    @RequirePermission(menu = "INCOME_COMM", perm = "READ")
    public ApiResponse<MarginSummaryResp> detailMargin(@PathVariable Long marginId) {
        return ApiResponse.ok(service.detailMargin(marginId));
    }

    @PostMapping("/margin/recalc")
    @RequirePermission(menu = "INCOME_COMM", perm = "CREATE")
    @DataChangeLog(menu = "INCOME_COMM", table = "margin_summary")
    public ApiResponse<Long> recalcMargin(@RequestParam String settleMonth,
                                          @RequestParam(required = false) Long agentId) {
        return ApiResponse.ok(service.recalcMargin(settleMonth, agentId));
    }
}
