package com.rtlabs.users.api;

import com.rtlabs.users.auth.AppUser;
import com.rtlabs.users.domain.UserProfile;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

  private final UserProfileService userProfileService;
  private final UserProfileMapper mapper;
  private final AccessAuditLogger accessAuditLogger;

  public UserController(UserProfileService userProfileService,
                        UserProfileMapper mapper,
                        AccessAuditLogger accessAuditLogger) {
    this.userProfileService = userProfileService;
    this.mapper = mapper;
    this.accessAuditLogger = accessAuditLogger;
  }

  // @PreAuthorize("hasAuthority('PROFILE:READ') and #principal.id == #id")
  @GetMapping("/{id}")
  public ResponseEntity<UserProfileDto> getUser(
      @PathVariable Long id,
      @AuthenticationPrincipal AppUser principal) {

    UserProfile profile = userProfileService.loadProfile(id);
    accessAuditLogger.log(principal.getUsername(), id);
    return ResponseEntity.ok(mapper.toDto(profile));
  }
}
