package com.gpf.pethospital.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gpf.pethospital.common.ApiResponse;
import com.gpf.pethospital.entity.User;
import com.gpf.pethospital.security.AuthUser;
import com.gpf.pethospital.service.UserService;
import com.gpf.pethospital.util.SecurityUtils;
// import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

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

    @GetMapping("/me")
    public ApiResponse<?> me() {
        AuthUser authUser = SecurityUtils.currentUser();
        if (authUser == null) {
            return ApiResponse.error(401, "unauthorized");
        }
        User user = userService.getById(authUser.getId());
        if (user != null) {
            user.setPassword(null);
        }
        return ApiResponse.success(user);
    }

    @PutMapping("/me")
    public ApiResponse<?> updateMe(@RequestBody User payload) {
        AuthUser authUser = SecurityUtils.currentUser();
        if (authUser == null) {
            return ApiResponse.error(401, "unauthorized");
        }
        User update = new User();
        update.setId(authUser.getId());
        update.setUsername(payload.getUsername());
        update.setPhone(payload.getPhone());
        update.setEmail(payload.getEmail());
        update.setAvatar(payload.getAvatar());
        userService.updateById(update);
        return ApiResponse.success("updated", null);
    }

    @GetMapping
    public ApiResponse<?> list(@RequestParam(defaultValue = "1") long page,
                               @RequestParam(defaultValue = "10") long size,
                               @RequestParam(required = false) String role) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (role != null && !role.isBlank()) {
            wrapper.eq(User::getRole, role);
        }
        Page<User> result = userService.page(new Page<>(page, size), wrapper);
        result.getRecords().forEach(u -> u.setPassword(null));
        return ApiResponse.success(result);
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    public ApiResponse<?> create(@RequestBody User user) {
        if (user.getPassword() == null || user.getPassword().isBlank()) {
            return ApiResponse.error(400, "password required");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        userService.save(user);
        return ApiResponse.success("created", null);
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/{id}/status")
    public ApiResponse<?> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        User update = new User();
        update.setId(id);
        update.setStatus(status);
        userService.updateById(update);
        return ApiResponse.success("updated", null);
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/{id}/reset-password")
    public ApiResponse<?> resetPassword(@PathVariable Long id, @RequestParam String newPassword) {
        User update = new User();
        update.setId(id);
        update.setPassword(passwordEncoder.encode(newPassword));
        userService.updateById(update);
        return ApiResponse.success("updated", null);
    }

    // @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/stats")
    public ApiResponse<?> stats() {
        Map<String, Object> data = new HashMap<>();
        data.put("total", userService.count());
        data.put("admins", userService.count(new LambdaQueryWrapper<User>().eq(User::getRole, "ADMIN")));
        data.put("doctors", userService.count(new LambdaQueryWrapper<User>().eq(User::getRole, "DOCTOR")));
        data.put("customers", userService.count(new LambdaQueryWrapper<User>().eq(User::getRole, "CUSTOMER")));
        return ApiResponse.success(data);
    }
}
