package com.rtlabs.accounts;

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/accounts")
public class AccountController {

  private final AccountRepository accountRepository;
  private final AccountMapper mapper;
  private final AuditLogger auditLogger;

  public AccountController(AccountRepository accountRepository,
                           AccountMapper mapper,
                           AuditLogger auditLogger) {
    this.accountRepository = accountRepository;
    this.mapper = mapper;
    this.auditLogger = auditLogger;
  }

  @GetMapping("/{accountId}")
  public ResponseEntity<AccountDto> getAccount(
      @PathVariable Long accountId,
      @AuthenticationPrincipal AppUser currentUser) {

    Account account = accountRepository.findById(accountId)
        .orElseThrow(() -> new AccountNotFoundException(accountId));

    auditLogger.logProfileAccess(currentUser.getUsername(), accountId);
    return ResponseEntity.ok(mapper.toDto(account));
  }
}
