package com.zioinfo.mes.uiws.system.controller;

import com.zioinfo.mes.common.ApiResponse;
import com.zioinfo.mes.uiws.system.dto.CodeGrpDetailDto;
import com.zioinfo.mes.uiws.system.dto.CodeGrpDto;
import com.zioinfo.mes.uiws.system.dto.CodeGrpSaveDto;
import com.zioinfo.mes.uiws.system.dto.CodeValueDto;
import com.zioinfo.mes.uiws.system.dto.PageResponse;
import com.zioinfo.mes.uiws.system.service.CodeService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 2.7 코드(codes) — 그룹목록/상세/CRUD/드롭다운값. base: /api/system/codes */
@RestController
@RequestMapping("/api/system/codes")
@RequiredArgsConstructor
public class CodeController {

    private final CodeService codeService;

    @GetMapping
    public ApiResponse<PageResponse<CodeGrpDto>> listGroups(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        return ApiResponse.ok(codeService.listGroups(keyword, page, size));
    }

    /** 드롭다운 공용 코드값 조회(정적 경로 우선). */
    @GetMapping("/group/{grpCd}/values")
    public ApiResponse<List<CodeValueDto>> getValues(@PathVariable("grpCd") String grpCd) {
        return ApiResponse.ok(codeService.getValues(grpCd));
    }

    @GetMapping("/{grpCd}")
    public ApiResponse<CodeGrpDetailDto> getGroup(@PathVariable("grpCd") String grpCd) {
        return ApiResponse.ok(codeService.getGroup(grpCd));
    }

    @PostMapping
    public ApiResponse<CodeGrpDetailDto> create(@Valid @RequestBody CodeGrpSaveDto dto) {
        return ApiResponse.ok(codeService.create(dto));
    }

    @PutMapping("/{grpCd}")
    public ApiResponse<CodeGrpDetailDto> update(@PathVariable("grpCd") String grpCd, @Valid @RequestBody CodeGrpSaveDto dto) {
        return ApiResponse.ok(codeService.update(grpCd, dto));
    }

    @DeleteMapping("/{grpCd}")
    public ApiResponse<Void> delete(@PathVariable("grpCd") String grpCd) {
        codeService.delete(grpCd);
        return ApiResponse.ok(null);
    }
}
