package com.cloudhandson.ddsbackoffice.service;

import com.cloudhandson.vpdbackoffice.service.DdsAuthorizationSynchronizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.stereotype.Component;

/** Republishes all local DDS MCP identities in the same request as an authorization change. */
@Component
public class DdsMcpAuthorizationChangeListener implements DdsAuthorizationSynchronizer {

  private static final Logger log = LoggerFactory.getLogger(DdsMcpAuthorizationChangeListener.class);
  private final DdsMcpEndUserPublisher publisher;

  public DdsMcpAuthorizationChangeListener(DdsMcpEndUserPublisher publisher) {
    this.publisher = publisher;
  }

  @Override
  public void synchronize(String reason) {
    try {
      var result = publisher.publish();
      log.info("DDS MCP authorization sync completed after {}: published={}, defaultDenied={}, revoked={}",
          reason, result.publishedUsers(), result.defaultDeniedUsers(), result.revokedUsers());
    } catch (RuntimeException exception) {
      throw new DataAccessResourceFailureException(
          "업무 권한 변경 뒤 DDS MCP 권한 동기화에 실패했습니다. DDS 게시 상태를 확인하세요.", exception);
    }
  }
}
