package cloud.nstart.terravault.ordinis.notifications.dispatcher;

import cloud.nstart.terravault.ordinis.notifications.channel.UserRef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Locale;
import java.util.Optional;

/**
 * Production {@link RecipientResolver} backed by a {@link UserDisplayPort} —
 * a narrow interface over {@code UserDisplayService} to avoid an explicit
 * compile-time dependency from ordinis-notifications on ordinis-rest-api.
 *
 * <p>The port is implemented in the app module (ordinis-app) which has
 * visibility over both modules. Tests can provide a mock port directly.
 *
 * <p>Locale: the user_display_cache table does not store locale; we default
 * to {@code ru} matching the existing {@code MessageRenderer.DEFAULT_LOCALE}
 * convention. When per-user locale is added, update this resolver.
 */
@Component
@ConditionalOnProperty(name = "ordinis.notifications.enabled", havingValue = "true", matchIfMissing = false)
public class UserDisplayRecipientResolver implements RecipientResolver {

  private static final Logger log = LoggerFactory.getLogger(UserDisplayRecipientResolver.class);

  private final UserDisplayPort userDisplayPort;

  public UserDisplayRecipientResolver(UserDisplayPort userDisplayPort) {
    this.userDisplayPort = userDisplayPort;
  }

  @Override
  public Optional<UserRef> resolveById(String userId) {
    if (userId == null || userId.isBlank()) return Optional.empty();

    Optional<UserDisplayPort.DisplayInfo> info = userDisplayPort.findById(userId);
    if (info.isEmpty()) {
      log.debug("RecipientResolver: user {} not found in display cache", userId);
      return Optional.empty();
    }

    UserDisplayPort.DisplayInfo d = info.get();
    // Phase A: email only; expressHuid/telegramChatId resolved later (Phase B/C).
    return Optional.of(new UserRef(userId, d.email(), null, null, Locale.forLanguageTag("ru")));
  }
}
