package com.ga.api.controller.org;

import com.ga.api.service.org.AgentService;
import com.ga.common.annotation.DataChangeLog;
import com.ga.common.annotation.RequirePermission;
import com.ga.common.excel.ExcelService;
import com.ga.common.model.ApiResponse;
import com.ga.common.model.PageResponse;
import com.ga.core.vo.org.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
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/agents")
@RequiredArgsConstructor
public class AgentController {

    private final AgentService agentService;
    private final ExcelService excelService;

    @GetMapping
    @RequirePermission(menu = "ORG_AGENT", perm = "READ")
    public ApiResponse<PageResponse<AgentResp>> list(@ModelAttribute AgentSearchParam param) {
        return ApiResponse.ok(agentService.list(param));
    }

    @GetMapping("/{agentId}")
    @RequirePermission(menu = "ORG_AGENT", perm = "READ")
    public ApiResponse<AgentResp> detail(@PathVariable Long agentId) {
        return ApiResponse.ok(agentService.detail(agentId));
    }

    @PostMapping
    @RequirePermission(menu = "ORG_AGENT", perm = "CREATE")
    @DataChangeLog(menu = "ORG_AGENT", table = "agent")
    public ApiResponse<Long> create(@Valid @RequestBody AgentSaveReq req) {
        return ApiResponse.ok(agentService.create(req));
    }

    @PutMapping("/{agentId}")
    @RequirePermission(menu = "ORG_AGENT", perm = "UPDATE")
    @DataChangeLog(menu = "ORG_AGENT", table = "agent")
    public ApiResponse<Void> update(@PathVariable Long agentId, @Valid @RequestBody AgentSaveReq req) {
        agentService.update(agentId, req);
        return ApiResponse.ok();
    }

    @PutMapping("/{agentId}/status")
    @RequirePermission(menu = "ORG_AGENT", perm = "UPDATE")
    @DataChangeLog(menu = "ORG_AGENT", table = "agent")
    public ApiResponse<Void> changeStatus(@PathVariable Long agentId, @RequestBody Map<String, String> body) {
        agentService.changeStatus(agentId, body.get("status"));
        return ApiResponse.ok();
    }

    @GetMapping("/{agentId}/history")
    @RequirePermission(menu = "ORG_AGENT", perm = "READ")
    public ApiResponse<List<AgentOrgHistoryResp>> history(@PathVariable Long agentId) {
        return ApiResponse.ok(agentService.history(agentId));
    }

    @GetMapping("/export")
    @RequirePermission(menu = "ORG_AGENT", perm = "EXPORT")
    public void export(@ModelAttribute AgentSearchParam param, HttpServletResponse response) {
        excelService.exportLargeExcel("설계사목록", AgentExcelVO.class,
                () -> agentService.exportCursor(param), response);
    }
}
