package com.tasteby.controller;

import com.tasteby.domain.Memo;
import com.tasteby.domain.Restaurant;
import com.tasteby.domain.Review;
import com.tasteby.security.AuthUtil;
import com.tasteby.service.MemoService;
import com.tasteby.service.ReviewService;
import com.tasteby.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

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

@RestController
@RequestMapping("/api/admin/users")
public class AdminUserController {

    private static final Logger log = LoggerFactory.getLogger(AdminUserController.class);
    private final UserService userService;
    private final ReviewService reviewService;
    private final MemoService memoService;

    public AdminUserController(UserService userService, ReviewService reviewService, MemoService memoService) {
        this.userService = userService;
        this.reviewService = reviewService;
        this.memoService = memoService;
    }

    @GetMapping
    public Map<String, Object> listUsers(
            @RequestParam(defaultValue = "50") int limit,
            @RequestParam(defaultValue = "0") int offset) {
        AuthUtil.requireAdmin();
        var users = userService.findAllWithCounts(limit, offset);
        int total = userService.countAll();
        return Map.of("users", users, "total", total);
    }

    @GetMapping("/{userId}/favorites")
    public List<Restaurant> userFavorites(@PathVariable String userId) {
        AuthUtil.requireAdmin();
        return reviewService.getUserFavorites(userId);
    }

    @GetMapping("/{userId}/reviews")
    public List<Review> userReviews(@PathVariable String userId) {
        AuthUtil.requireAdmin();
        return reviewService.findByUser(userId, 100, 0);
    }

    @GetMapping("/{userId}/memos")
    public List<Memo> userMemos(@PathVariable String userId) {
        AuthUtil.requireAdmin();
        return memoService.findByUser(userId);
    }

    @PatchMapping("/{userId}/admin")
    public Map<String, Object> updateAdmin(@PathVariable String userId, @RequestBody Map<String, Boolean> body) {
        var currentUser = AuthUtil.requireAdmin();
        if (userId.equals(currentUser.getSubject())) {
            throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST, "자기 자신의 관리자 권한은 변경할 수 없습니다");
        }
        boolean admin = Boolean.TRUE.equals(body.get("admin"));
        userService.updateAdmin(userId, admin);
        log.info("[ADMIN] User {} set admin={} for user {}", currentUser.getSubject(), admin, userId);
        return Map.of("success", true, "user_id", userId, "is_admin", admin);
    }
}
