package com.gcsc.connection.user.controller;

import com.gcsc.connection.common.dto.ApiResponse;
import com.gcsc.connection.user.dto.CreateUserRequest;
import com.gcsc.connection.user.dto.UpdateUserRequest;
import com.gcsc.connection.user.dto.UserResponse;
import com.gcsc.connection.user.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;

import java.util.List;

/**
 * 사용자 관리 API
 */
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 전체 사용자 목록 조회
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<UserResponse>>> getUsers() {
        List<UserResponse> users = userService.getUsers();
        return ResponseEntity.ok(ApiResponse.ok(users));
    }

    /**
     * 사용자 생성
     */
    @PostMapping
    public ResponseEntity<ApiResponse<UserResponse>> createUser(
            @RequestBody @Valid CreateUserRequest request) {
        UserResponse user = userService.createUser(request);
        return ResponseEntity.ok(ApiResponse.ok(user));
    }

    /**
     * 사용자 단건 조회 (ADMIN/MANAGER 또는 본인)
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<UserResponse>> getUser(@PathVariable Long id) {
        String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
        if (!isAdminOrManager() && !currentUserId.equals(String.valueOf(id))) {
            throw new AccessDeniedException("접근 권한이 없습니다");
        }
        UserResponse user = userService.getUser(id);
        return ResponseEntity.ok(ApiResponse.ok(user));
    }

    /**
     * 사용자 수정 (ADMIN은 모든 사용자, 본인은 자기 정보만)
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<UserResponse>> updateUser(
            @PathVariable Long id,
            @RequestBody @Valid UpdateUserRequest request) {
        String currentUserId = SecurityContextHolder.getContext().getAuthentication().getName();
        if (!isAdmin() && !currentUserId.equals(String.valueOf(id))) {
            throw new AccessDeniedException("접근 권한이 없습니다");
        }
        UserResponse user = userService.updateUser(id, request);
        return ResponseEntity.ok(ApiResponse.ok(user));
    }

    /**
     * 사용자 비활성화 (소프트 삭제)
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deactivateUser(@PathVariable Long id) {
        userService.deactivateUser(id);
        return ResponseEntity.ok(ApiResponse.ok(null, "사용자가 비활성화되었습니다"));
    }

    private boolean isAdmin() {
        return SecurityContextHolder.getContext().getAuthentication()
            .getAuthorities().stream()
            .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
    }

    private boolean isAdminOrManager() {
        return SecurityContextHolder.getContext().getAuthentication()
            .getAuthorities().stream()
            .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN")
                || a.getAuthority().equals("ROLE_MANAGER"));
    }
}
