package com.realnet.users.controller;

import com.realnet.users.entity.User;
import com.realnet.users.model.UserProfileUpdateRequest;
import com.realnet.users.service.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/users")
public class UserProfileController {

    @Autowired
    private UserProfileService userProfileService;

    // Helper method to get current authenticated user's ID
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // This assumes the principal is a User object or has an ID field
        // In a real app, you'd likely have a custom UserDetails implementation
        // For now, we'll assume the username is the ID for simplicity or fetch from DB
        // This needs to be properly integrated with Spring Security's UserDetails
        // For demonstration, let's return a dummy ID or throw an exception
        throw new UnsupportedOperationException("User ID retrieval not yet implemented for current principal.");
    }

    @GetMapping("/me")
    public ResponseEntity<User> getMyProfile() {
        // This needs to be replaced with actual user ID from authenticated principal
        // For now, using a placeholder or assuming ID is passed
        Long userId = getCurrentUserId(); // Replace with actual logic to get authenticated user's ID
        Optional<User> user = userProfileService.getUserProfile(userId);
        return user.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/me")
    public ResponseEntity<User> updateMyProfile(@Valid @RequestBody UserProfileUpdateRequest updateRequest) {
        Long userId = getCurrentUserId(); // Replace with actual logic to get authenticated user's ID
        try {
            User updatedUser = userProfileService.updateUserProfile(userId, updateRequest);
            return ResponseEntity.ok(updatedUser);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(null); // Or more specific error handling
        }
    }

    @GetMapping("/search")
    public ResponseEntity<List<User>> searchUsers(@RequestParam String query) {
        List<User> users = userProfileService.searchUsers(query);
        return ResponseEntity.ok(users);
    }
}