package com.dne.ems.controller;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.dne.ems.dto.PageDTO;
import com.dne.ems.dto.UserCreationRequest;
import com.dne.ems.dto.UserRoleUpdateRequest;
import com.dne.ems.dto.UserUpdateRequest;
import com.dne.ems.model.UserAccount;
import com.dne.ems.model.enums.Role;
import com.dne.ems.service.PersonnelService;
import com.dne.ems.service.UserAccountService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

/**
 * 人员管理控制器，处理用户账号的CRUD操作
 *
 * <p>主要功能包括：
 * <ul>
 *   <li>用户账号创建</li>
 *   <li>用户信息查询与更新</li>
 *   <li>用户角色管理</li>
 *   <li>用户删除</li>
 * </ul>
 *
 * @author DNE开发团队
 * @version 1.0
 * @since 2024
 */
@RestController
@RequestMapping("/api/personnel")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class PersonnelController {

    private final PersonnelService personnelService;
    private final UserAccountService userAccountService;

    /**
     * 创建新用户
     *
     * @param request 包含用户信息的请求体
     * @return 创建成功的用户实体
     * @throws UserAlreadyExistsException 如果用户名或邮箱已存在
     */
    @PostMapping("/users")
    @ResponseStatus(HttpStatus.CREATED)
    public UserAccount createUser(@RequestBody @Valid UserCreationRequest request) {
        return personnelService.createUser(request);
    }

    /**
     * 获取用户分页列表
     *
     * @param role 角色过滤条件(可选)
     * @param name 姓名过滤条件(可选，不区分大小写)
     * @param pageable 分页参数
     * @return 用户分页列表
     */
    @Operation(summary = "Get a paginated list of users", description = "Retrieves a list of users, with optional filtering by role and name.")
    @GetMapping("/users")
    @PreAuthorize("hasRole('ADMIN') or hasRole('GRID_WORKER')")
    public ResponseEntity<PageDTO<UserAccount>> getUsers(
            @Parameter(description = "Filter by user role") @RequestParam(required = false) Role role,
            @Parameter(description = "Filter by user name (case-insensitive search)") @RequestParam(required = false) String name,
            Pageable pageable) {
        Page<UserAccount> usersPage = personnelService.getUsers(role, name, pageable);
        PageDTO<UserAccount> userPageDTO = new PageDTO<>(
                usersPage.getContent(),
                usersPage.getTotalElements(),
                usersPage.getTotalPages(),
                usersPage.getNumber(),
                usersPage.getSize()
        );
        return ResponseEntity.ok(userPageDTO);
    }

    /**
     * 根据ID获取用户详情
     *
     * @param userId 用户ID
     * @return 用户详情
     * @throws ResourceNotFoundException 如果用户不存在
     */
    @Operation(summary = "Get user by ID", description = "Fetches the details of a specific user by their ID.")
    @GetMapping("/users/{userId}")
    public ResponseEntity<UserAccount> getUserById(@PathVariable Long userId) {
        UserAccount user = userAccountService.getUserById(userId);
        user.setPassword(null); // Do not expose password
        return ResponseEntity.ok(user);
    }

    /**
     * 更新用户信息
     *
     * @param userId 用户ID
     * @param request 包含更新信息的请求体
     * @return 更新后的用户实体
     * @throws ResourceNotFoundException 如果用户不存在
     */
    @PatchMapping("/users/{userId}")
    public ResponseEntity<UserAccount> updateUser(
            @PathVariable Long userId,
            @RequestBody UserUpdateRequest request) {
        UserAccount updatedUser = personnelService.updateUser(userId, request);
        return ResponseEntity.ok(updatedUser);
    }

    /**
     * 更新用户角色
     *
     * @param userId 用户ID
     * @param request 包含角色信息的请求体
     * @return 更新后的用户实体
     * @throws ResourceNotFoundException 如果用户不存在
     * @throws InvalidOperationException 如果角色更新无效
     */
    @PutMapping("/users/{userId}/role")
    public ResponseEntity<UserAccount> updateUserRole(
            @PathVariable Long userId,
            @RequestBody @Valid UserRoleUpdateRequest request) {
        UserAccount updatedUser = userAccountService.updateUserRole(userId, request);
        updatedUser.setPassword(null); // Do not expose password
        return ResponseEntity.ok(updatedUser);
    }

    /**
     * 删除用户
     *
     * @param userId 用户ID
     * @throws ResourceNotFoundException 如果用户不存在
     */
    @DeleteMapping("/users/{userId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@PathVariable Long userId) {
        personnelService.deleteUser(userId);
    }
} 