package com.example.scaffold.controller;

import com.example.scaffold.dto.UserCreateRequest;
import com.example.scaffold.entity.User;
import com.example.scaffold.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * 用户控制器 - RESTful API 演示
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    /**
     * GET - 查询所有用户
     */
    @GetMapping
    public List<User> list() {
        return userService.findAll();
    }
    
    /**
     * GET - 根据 ID 查询
     */
    @GetMapping("/{id}")
    public ResponseEntity<User> getById(@PathVariable Long id) {
        return userService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * GET - 搜索用户
     */
    @GetMapping("/search")
    public List<User> search(@RequestParam String username) {
        return userService.searchByUsername(username);
    }
    
    /**
     * POST - 创建用户
     */
    @PostMapping
    public ResponseEntity<User> create(@Valid @RequestBody UserCreateRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setBio(request.getBio());
        user.setActive(true);
        
        User saved = userService.save(user);
        return ResponseEntity.ok(saved);
    }
    
    /**
     * PUT - 更新用户
     */
    @PutMapping("/{id}")
    public ResponseEntity<User> update(@PathVariable Long id, @Valid @RequestBody UserCreateRequest request) {
        return userService.findById(id)
                .map(existing -> {
                    existing.setUsername(request.getUsername());
                    existing.setEmail(request.getEmail());
                    existing.setPhone(request.getPhone());
                    existing.setBio(request.getBio());
                    return ResponseEntity.ok(userService.save(existing));
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * DELETE - 删除用户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        userService.deleteById(id);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * GET - 统计
     */
    @GetMapping("/count")
    public Map<String, Long> count() {
        return Map.of("count", userService.count());
    }
}