package com.ga.api.controller.org;

import com.ga.api.service.org.OrganizationService;
import com.ga.common.annotation.DataChangeLog;
import com.ga.common.annotation.RequirePermission;
import com.ga.common.model.ApiResponse;
import com.ga.core.vo.org.OrganizationResp;
import com.ga.core.vo.org.OrganizationSaveReq;
import com.ga.core.vo.org.OrganizationVO;
import jakarta.validation.Valid;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "조직 관리")
@RestController
@RequestMapping("/api/orgs")
@RequiredArgsConstructor
public class OrganizationController {

    private final OrganizationService service;

    @GetMapping("/tree")
    @RequirePermission(menu = "ORG_TREE", perm = "READ")
    public ApiResponse<List<OrganizationResp>> tree() {
        return ApiResponse.ok(service.getTree());
    }

    @GetMapping
    @RequirePermission(menu = "ORG_TREE", perm = "READ")
    public ApiResponse<List<OrganizationResp>> list(@RequestParam(required = false) String keyword,
                                                    @RequestParam(required = false) String orgType,
                                                    @RequestParam(required = false) String isActive) {
        return ApiResponse.ok(service.list(keyword, orgType, isActive));
    }

    @GetMapping("/{orgId}")
    @RequirePermission(menu = "ORG_TREE", perm = "READ")
    public ApiResponse<OrganizationVO> detail(@PathVariable Long orgId) {
        return ApiResponse.ok(service.get(orgId));
    }

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

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

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