package com.xly.erp.module.mod.controller;

import com.xly.erp.common.response.Result;
import com.xly.erp.module.mod.dto.CreateModuleDTO;
import com.xly.erp.module.mod.dto.UpdateModuleDTO;
import com.xly.erp.module.mod.service.ModuleService;
import com.xly.erp.module.mod.vo.ModuleTreeVO;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/api/mod")
public class ModuleController {

    private final ModuleService moduleService;

    public ModuleController(ModuleService moduleService) {
        this.moduleService = moduleService;
    }

    @PostMapping("/modules")
    public Result<Map<String, Integer>> create(@Valid @RequestBody CreateModuleDTO dto) {
        Integer id = moduleService.create(dto);
        return Result.ok(Map.of("iIncrement", id));
    }

    @PutMapping("/modules/{id}")
    public Result<Map<String, Integer>> update(@PathVariable Integer id,
                                               @Valid @RequestBody UpdateModuleDTO dto) {
        Integer updated = moduleService.update(id, dto);
        return Result.ok(Map.of("iIncrement", updated));
    }

    @DeleteMapping("/modules/{id}")
    public Result<Void> delete(@PathVariable Integer id) {
        moduleService.delete(id);
        return Result.ok();
    }

    @GetMapping("/modules")
    public Result<List<ModuleTreeVO>> list(@RequestParam(required = false) String keyword) {
        return Result.ok(moduleService.listTree(keyword));
    }
}
