package com.example.demo.controller;

import com.example.demo.common.ApiResponse;
import com.example.demo.dto.UserRequest;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

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

    @GetMapping
    public ApiResponse<List<User>> getAllUsers() {
        return ApiResponse.ok(userService.findAll());
    }

    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        return ApiResponse.ok(userService.findById(id));
    }

    @PostMapping
    public ApiResponse<User> createUser(@Valid @RequestBody UserRequest req) {
        User user = new User(null, req.name(), req.email(), req.age());
        return ApiResponse.ok("创建成功", userService.create(user));
    }

    @PutMapping("/{id}")
    public ApiResponse<User> updateUser(@PathVariable Long id, @Valid @RequestBody UserRequest req) {
        User user = new User(id, req.name(), req.email(), req.age());
        return ApiResponse.ok("更新成功", userService.update(id, user));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return ApiResponse.ok("删除成功", null);
    }

    @GetMapping("/search")
    public ApiResponse<List<User>> searchUsers(@RequestParam String name) {
        return ApiResponse.ok(userService.findByName(name));
    }
}
