package com.ga.api.controller.statement;

import com.ga.api.service.statement.CommissionStatementService;
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.CommissionStatementResp;
import com.ga.core.vo.settle.CommissionStatementSaveReq;
import com.ga.core.vo.settle.CommissionStatementSearchParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Tag(name = "수수료 명세서")
@Validated
@RestController
@RequestMapping("/api/statements")
@RequiredArgsConstructor
public class CommissionStatementController {

    private final CommissionStatementService statementService;

    @GetMapping
    @RequirePermission(menu = "STATEMENT", perm = "READ")
    public ApiResponse<PageResponse<CommissionStatementResp>> list(@ModelAttribute CommissionStatementSearchParam param) {
        return ApiResponse.ok(statementService.list(param));
    }

    @GetMapping("/{statementId}")
    @RequirePermission(menu = "STATEMENT", perm = "READ")
    public ApiResponse<CommissionStatementResp> detail(@PathVariable Long statementId) {
        return ApiResponse.ok(statementService.detail(statementId));
    }

    @Operation(summary = "명세서 단건 발급")
    @PostMapping("/generate")
    @RequirePermission(menu = "STATEMENT", perm = "CREATE")
    @DataChangeLog(menu = "STATEMENT", table = "commission_statement")
    public ApiResponse<Long> generate(@Valid @RequestBody CommissionStatementSaveReq req) {
        return ApiResponse.ok(statementService.generate(req));
    }

    @Operation(summary = "명세서 월별 일괄 발급")
    @PostMapping("/generate-for-month")
    @RequirePermission(menu = "STATEMENT", perm = "CREATE")
    @DataChangeLog(menu = "STATEMENT", table = "commission_statement")
    public ApiResponse<Void> generateForMonth(
            @Pattern(regexp = "\\d{6}", message = "settleMonth는 YYYYMM 형식이어야 합니다") @RequestParam String settleMonth,
            @RequestParam String statementType) {
        statementService.generateForMonth(settleMonth, statementType);
        return ApiResponse.ok();
    }

    @Operation(summary = "명세서 다운로드")
    @GetMapping("/{statementId}/download")
    @RequirePermission(menu = "STATEMENT", perm = "READ")
    public void download(@PathVariable Long statementId, HttpServletResponse response) throws IOException {
        byte[] content = statementService.download(statementId);
        String encoded = URLEncoder.encode("수수료명세서_" + statementId + ".xlsx", StandardCharsets.UTF_8)
                .replace("+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
        response.setContentLength(content.length);
        response.getOutputStream().write(content);
    }

    @Operation(summary = "명세서 취소")
    @PutMapping("/{statementId}/cancel")
    @RequirePermission(menu = "STATEMENT", perm = "UPDATE")
    @DataChangeLog(menu = "STATEMENT", table = "commission_statement")
    public ApiResponse<Void> cancel(@PathVariable Long statementId) {
        statementService.cancel(statementId);
        return ApiResponse.ok();
    }
}
