package com.ga.api.controller.accounting;

import com.ga.api.service.accounting.AccountingCloseService;
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.accounting.AccountBalanceSnapshotVO;
import com.ga.core.vo.accounting.AccountingCloseResp;
import com.ga.core.vo.accounting.AccountingCloseSaveReq;
import com.ga.core.vo.accounting.AccountingCloseSearchParam;
import io.swagger.v3.oas.annotations.Operation;
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/accounting-closes")
@RequiredArgsConstructor
public class AccountingCloseController {

    private final AccountingCloseService service;

    @GetMapping
    @Operation(summary = "회계 결산 목록")
    @RequirePermission(menu = "ACCOUNTING_CLOSE", perm = "READ")
    public ApiResponse<PageResponse<AccountingCloseResp>> list(@ModelAttribute AccountingCloseSearchParam param) {
        return ApiResponse.ok(service.list(param));
    }

    @GetMapping("/{id}")
    @Operation(summary = "회계 결산 상세")
    @RequirePermission(menu = "ACCOUNTING_CLOSE", perm = "READ")
    public ApiResponse<AccountingCloseResp> detail(@PathVariable Long id) {
        return ApiResponse.ok(service.detail(id));
    }

    @GetMapping("/{id}/snapshots")
    @Operation(summary = "계정과목별 잔액 스냅샷")
    @RequirePermission(menu = "ACCOUNTING_CLOSE", perm = "READ")
    public ApiResponse<List<AccountBalanceSnapshotVO>> snapshots(@PathVariable Long id) {
        return ApiResponse.ok(service.snapshots(id));
    }

    @PostMapping("/draft")
    @Operation(summary = "결산 DRAFT 생성")
    @RequirePermission(menu = "ACCOUNTING_CLOSE", perm = "CREATE")
    @DataChangeLog(menu = "ACCOUNTING_CLOSE", table = "accounting_close")
    public ApiResponse<Long> createDraft(@Valid @RequestBody AccountingCloseSaveReq req) {
        return ApiResponse.ok(service.createDraft(req));
    }

    @PostMapping("/{id}/close")
    @Operation(summary = "결산 마감 실행")
    @RequirePermission(menu = "ACCOUNTING_CLOSE", perm = "EXECUTE")
    @DataChangeLog(menu = "ACCOUNTING_CLOSE", table = "accounting_close")
    public ApiResponse<AccountingCloseResp> close(@PathVariable Long id) {
        return ApiResponse.ok(service.close(id));
    }

    @PostMapping("/{id}/reopen")
    @Operation(summary = "결산 재오픈")
    @RequirePermission(menu = "ACCOUNTING_CLOSE", perm = "APPROVE")
    @DataChangeLog(menu = "ACCOUNTING_CLOSE", table = "accounting_close")
    public ApiResponse<Void> reopen(@PathVariable Long id, @RequestBody Map<String, String> body) {
        service.reopen(id, body.get("reopenReason"));
        return ApiResponse.ok();
    }
}
