package com.lesingle.creation.controller;

import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.dto.user.CreateUserDTO;
import com.lesingle.creation.dto.user.UpdateUserDTO;
import com.lesingle.creation.dto.user.UserQueryDTO;
import com.lesingle.creation.service.UserService;
import com.lesingle.creation.vo.user.UserDetailVO;
import com.lesingle.creation.vo.user.UserListVO;
import com.lesingle.creation.vo.user.UserStatsVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理控制器
 */
@Tag(name = "用户管理")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @PostMapping
    @Operation(summary = "创建用户")
    @PreAuthorize("hasAuthority('user:create')")
    public Result<UserDetailVO> create(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated CreateUserDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long operatorId = userPrincipal.getUserId();
        UserDetailVO result = userService.create(dto, tenantId, operatorId);
        return Result.success(result);
    }

    @GetMapping("/stats")
    @Operation(summary = "用户统计（仅超管）")
    @PreAuthorize("hasAuthority('super_admin')")
    public Result<UserStatsVO> getStats() {
        UserStatsVO result = userService.getStats();
        return Result.success(result);
    }

    @GetMapping
    @Operation(summary = "用户列表")
    @PreAuthorize("hasAuthority('user:read')")
    public Result<com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserListVO>> pageList(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String userType,
            @RequestParam(required = false) String userSource,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        Long tenantId = userPrincipal.getTenantId();
        boolean isSuperTenant = userPrincipal.isSuperTenant();

        UserQueryDTO queryDTO = new UserQueryDTO();
        queryDTO.setKeyword(keyword);
        queryDTO.setUserType(userType);
        queryDTO.setUserSource(userSource);
        queryDTO.setStatus(status);
        queryDTO.setPage(page);
        queryDTO.setPageSize(pageSize);

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserListVO> result =
                userService.pageList(queryDTO, tenantId, isSuperTenant);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "用户详情")
    @PreAuthorize("hasAuthority('user:read')")
    public Result<UserDetailVO> detail(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        boolean isSuperTenant = userPrincipal.isSuperTenant();
        UserDetailVO result = userService.detail(id, tenantId, isSuperTenant);
        return Result.success(result);
    }

    @PatchMapping("/{id}/status")
    @Operation(summary = "更新用户状态")
    @PreAuthorize("hasAuthority('user:manage')")
    public Result<UserDetailVO> updateStatus(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id,
            @RequestParam String status) {
        Long operatorId = userPrincipal.getUserId();
        UserDetailVO result = userService.updateStatus(id, status, operatorId);
        return Result.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新用户")
    @PreAuthorize("hasAuthority('user:update')")
    public Result<UserDetailVO> update(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id,
            @RequestBody @Validated UpdateUserDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        UserDetailVO result = userService.update(id, dto, tenantId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户")
    @PreAuthorize("hasAuthority('user:delete')")
    public Result<Void> delete(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        userService.delete(id, tenantId);
        return Result.success();
    }
}
