package com.zioinfo.mall.category;

import com.zioinfo.mall.category.mapper.CategoryMapper;
import com.zioinfo.mall.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 카탈로그 카테고리 API — /api/mall/category. GET 공개, 변경 MANAGER+. */
@RestController
@RequestMapping("/api/mall/category")
@RequiredArgsConstructor
public class CategoryController {

    private final CategoryMapper mapper;

    @GetMapping
    public ApiResponse<List<MallCategory>> list(@RequestParam(required = false) Long parentId,
                                                @RequestParam(required = false) Boolean children) {
        if (Boolean.TRUE.equals(children) || parentId != null) {
            return ApiResponse.ok(mapper.findByParent(parentId));
        }
        return ApiResponse.ok(mapper.findAll());
    }

    @GetMapping("/tree")
    public ApiResponse<List<MallCategory>> tree() {
        return ApiResponse.ok(mapper.findAll());
    }

    @GetMapping("/{id}")
    public ApiResponse<MallCategory> get(@PathVariable Long id) {
        return ApiResponse.ok(mapper.findById(id));
    }

    @PostMapping
    public ApiResponse<MallCategory> create(@RequestBody MallCategory c) {
        mapper.insert(c);
        return ApiResponse.ok(c);
    }

    @PutMapping("/{id}")
    public ApiResponse<MallCategory> update(@PathVariable Long id, @RequestBody MallCategory c) {
        c.setId(id);
        mapper.update(c);
        return ApiResponse.ok(mapper.findById(id));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        mapper.delete(id);
        return ApiResponse.ok(null);
    }
}
