package com.ga.api.controller.system;

import com.ga.api.service.system.RoleService;
import com.ga.common.annotation.DataChangeLog;
import com.ga.common.annotation.RequirePermission;
import com.ga.common.model.ApiResponse;
import com.ga.core.vo.user.RoleVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "역할 관리")
@RestController
@RequestMapping("/api/system/roles")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;

    @GetMapping
    @RequirePermission(menu = "SYSTEM_ROLE", perm = "READ")
    public ApiResponse<List<RoleVO>> list() {
        return ApiResponse.ok(roleService.list());
    }

    @GetMapping("/{roleId}")
    @RequirePermission(menu = "SYSTEM_ROLE", perm = "READ")
    public ApiResponse<RoleVO> detail(@PathVariable Long roleId) {
        return ApiResponse.ok(roleService.detail(roleId));
    }

    @GetMapping("/{roleId}/permissions")
    @RequirePermission(menu = "SYSTEM_ROLE", perm = "READ")
    public ApiResponse<List<Map<String, Object>>> permissions(@PathVariable Long roleId) {
        return ApiResponse.ok(roleService.permissions(roleId));
    }

    @PostMapping
    @RequirePermission(menu = "SYSTEM_ROLE", perm = "CREATE")
    @DataChangeLog(menu = "SYSTEM_ROLE", table = "role")
    public ApiResponse<Long> create(@RequestBody RoleVO vo) {
        return ApiResponse.ok(roleService.create(vo));
    }

    @PutMapping("/{roleId}")
    @RequirePermission(menu = "SYSTEM_ROLE", perm = "UPDATE")
    @DataChangeLog(menu = "SYSTEM_ROLE", table = "role")
    public ApiResponse<Void> update(@PathVariable Long roleId, @RequestBody RoleVO vo) {
        roleService.update(roleId, vo);
        return ApiResponse.ok();
    }

    @DeleteMapping("/{roleId}")
    @RequirePermission(menu = "SYSTEM_ROLE", perm = "DELETE")
    @DataChangeLog(menu = "SYSTEM_ROLE", table = "role")
    public ApiResponse<Void> delete(@PathVariable Long roleId) {
        roleService.delete(roleId);
        return ApiResponse.ok();
    }

    @PutMapping("/{roleId}/permissions")
    @RequirePermission(menu = "SYSTEM_ROLE", perm = "UPDATE")
    @DataChangeLog(menu = "SYSTEM_ROLE", table = "role_permission")
    public ApiResponse<Void> savePermissions(@PathVariable Long roleId,
                                             @RequestBody List<Map<String, Object>> permissions) {
        roleService.savePermissions(roleId, permissions);
        return ApiResponse.ok();
    }
}
