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

import com.xly.erp.common.response.Result;
import com.xly.erp.module.usr.dto.CreateUserDTO;
import com.xly.erp.module.usr.dto.UpdateUserDTO;
import com.xly.erp.module.usr.service.UserService;
import com.xly.erp.module.usr.vo.PermissionCategoryVO;
import com.xly.erp.module.usr.vo.UserListVO;
import jakarta.validation.Valid;
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/usr")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/users")
    public Result<Map<String, Object>> create(@Valid @RequestBody CreateUserDTO dto) {
        return Result.ok(userService.create(dto));
    }

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

    @GetMapping("/users")
    public Result<Map<String, Object>> list(@RequestParam(required = false) String field,
                                            @RequestParam(required = false) String match,
                                            @RequestParam(required = false) String value,
                                            @RequestParam(required = false) Integer pageNum,
                                            @RequestParam(required = false) Integer pageSize) {
        return Result.ok(userService.list(field, match, value, pageNum, pageSize));
    }

    @GetMapping("/users/{id}")
    public Result<UserListVO> detail(@PathVariable Integer id) {
        return Result.ok(userService.detail(id));
    }

    @GetMapping("/permission-categories")
    public Result<List<PermissionCategoryVO>> permissionCategories() {
        return Result.ok(userService.listPermissionCategories());
    }
}
