package com.erp.user.controller;

import com.erp.user.entity.User;
import com.erp.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    /**
     * 获取用户列表
     */
    @GetMapping
    public ResponseEntity<List<User>> listUsers(
            @RequestParam(value = "tenantId", required = false) Long tenantId,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "20") Integer size) {
        log.info("查询用户列表: tenantId={}, username={}, page={}, size={}", 
                tenantId, username, page, size);
        List<User> users = userService.listUsers(tenantId, username, page, size);
        return ResponseEntity.ok(users);
    }
    
    /**
     * 获取用户详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
        log.info("查询用户详情: id={}", id);
        User user = userService.getUserById(id);
        return ResponseEntity.ok(user);
    }
    
    /**
     * 创建用户
     */
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        log.info("创建用户: username={}, email={}", user.getUsername(), user.getEmail());
        User createdUser = userService.createUser(user);
        return ResponseEntity.ok(createdUser);
    }
    
    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
        log.info("更新用户: id={}", id);
        user.setId(id);
        User updatedUser = userService.updateUser(user);
        return ResponseEntity.ok(updatedUser);
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
        log.info("删除用户: id={}", id);
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 启用/禁用用户
     */
    @PostMapping("/{id}/toggle-status")
    public ResponseEntity<User> toggleUserStatus(@PathVariable("id") Long id) {
        log.info("切换用户状态: id={}", id);
        User user = userService.toggleUserStatus(id);
        return ResponseEntity.ok(user);
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("User Service is healthy");
    }
}
