package com.ga.api.controller.contract;

import com.ga.api.service.contract.AgentContractService;
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.contract.AgentContractResp;
import com.ga.core.vo.contract.AgentContractSaveReq;
import com.ga.core.vo.contract.AgentContractSearchParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "위촉계약 관리")
@RestController
@RequestMapping("/api/agent-contracts")
@RequiredArgsConstructor
public class AgentContractController {

    private final AgentContractService service;

    @GetMapping
    @RequirePermission(menu = "AGENT_CONTRACT", perm = "READ")
    public ApiResponse<PageResponse<AgentContractResp>> list(@ModelAttribute AgentContractSearchParam param) {
        return ApiResponse.ok(service.list(param));
    }

    @GetMapping("/{contractId}")
    @RequirePermission(menu = "AGENT_CONTRACT", perm = "READ")
    public ApiResponse<AgentContractResp> detail(@PathVariable Long contractId) {
        return ApiResponse.ok(service.detail(contractId));
    }

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

    @PutMapping("/{contractId}")
    @RequirePermission(menu = "AGENT_CONTRACT", perm = "UPDATE")
    @DataChangeLog(menu = "AGENT_CONTRACT", table = "agent_contract")
    public ApiResponse<Void> update(@PathVariable Long contractId,
                                    @Valid @RequestBody AgentContractSaveReq req) {
        service.update(contractId, req);
        return ApiResponse.ok();
    }

    @PostMapping("/{contractId}/terminate")
    @RequirePermission(menu = "AGENT_CONTRACT", perm = "UPDATE")
    @DataChangeLog(menu = "AGENT_CONTRACT", table = "agent_contract")
    public ApiResponse<Void> terminate(@PathVariable Long contractId,
                                       @RequestBody Map<String, String> body) {
        service.terminate(contractId, body.get("reason"));
        return ApiResponse.ok();
    }

    @DeleteMapping("/{contractId}")
    @RequirePermission(menu = "AGENT_CONTRACT", perm = "DELETE")
    @DataChangeLog(menu = "AGENT_CONTRACT", table = "agent_contract")
    public ApiResponse<Void> delete(@PathVariable Long contractId) {
        service.delete(contractId);
        return ApiResponse.ok();
    }
}
