package com.ga.api.controller.dict;

import com.ga.api.service.dict.DataDictionaryService;
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.dict.DataDictionaryFullResp;
import com.ga.core.vo.dict.DataDictionaryResp;
import com.ga.core.vo.dict.DataDictionarySaveReq;
import com.ga.core.vo.dict.DataDictionarySearchParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "데이터 사전")
@RestController
@RequestMapping("/api/data-dictionary")
@RequiredArgsConstructor
public class DataDictionaryController {

    private final DataDictionaryService dataDictionaryService;

    @GetMapping
    @RequirePermission(menu = "SYSTEM_DATA_DICT", perm = "READ")
    public ApiResponse<PageResponse<DataDictionaryResp>> list(@ModelAttribute DataDictionarySearchParam param) {
        return ApiResponse.ok(dataDictionaryService.list(param));
    }

    @GetMapping("/tables")
    @RequirePermission(menu = "SYSTEM_DATA_DICT", perm = "READ")
    public ApiResponse<List<String>> tables() {
        return ApiResponse.ok(dataDictionaryService.tables());
    }

    @GetMapping("/full")
    @RequirePermission(menu = "SYSTEM_DATA_DICT", perm = "READ")
    public ApiResponse<List<DataDictionaryFullResp>> full(
            @RequestParam(required = false) String tableName) {
        return ApiResponse.ok(dataDictionaryService.full(tableName));
    }

    @GetMapping("/{dictId}")
    @RequirePermission(menu = "SYSTEM_DATA_DICT", perm = "READ")
    public ApiResponse<DataDictionaryResp> detail(@PathVariable Long dictId) {
        return ApiResponse.ok(dataDictionaryService.detail(dictId));
    }

    @PostMapping
    @RequirePermission(menu = "SYSTEM_DATA_DICT", perm = "CREATE")
    @DataChangeLog(menu = "SYSTEM_DATA_DICT", table = "data_dictionary")
    public ApiResponse<Void> create(@Valid @RequestBody DataDictionarySaveReq req) {
        dataDictionaryService.create(req);
        return ApiResponse.ok();
    }

    @PutMapping("/{dictId}")
    @RequirePermission(menu = "SYSTEM_DATA_DICT", perm = "UPDATE")
    @DataChangeLog(menu = "SYSTEM_DATA_DICT", table = "data_dictionary")
    public ApiResponse<Void> update(@PathVariable Long dictId,
                                    @Valid @RequestBody DataDictionarySaveReq req) {
        dataDictionaryService.update(dictId, req);
        return ApiResponse.ok();
    }

    @DeleteMapping("/{dictId}")
    @RequirePermission(menu = "SYSTEM_DATA_DICT", perm = "DELETE")
    @DataChangeLog(menu = "SYSTEM_DATA_DICT", table = "data_dictionary")
    public ApiResponse<Void> delete(@PathVariable Long dictId) {
        dataDictionaryService.delete(dictId);
        return ApiResponse.ok();
    }
}
