package cloud.nstart.terravault.ordinis.restapi.dto.webhook;

import cloud.nstart.terravault.ordinis.domain.DataScope;
import cloud.nstart.terravault.ordinis.domain.webhook.WebhookSubscription;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;

/**
 * Response для list/get/update endpoints. {@link #hmacSecret} ВСЕГДА
 * замаскирован ({@code sk_****<last4>}). Полный secret виден только в
 * response создания (single-time reveal).
 */
public record WebhookSubscriptionResponse(
    UUID id,
    String name,
    String url,
    List<DataScope> scopeFilter,
    List<String> dictionaryFilter,
    List<String> eventTypeFilter,
    String hmacSecret,
    boolean active,
    OffsetDateTime createdAt,
    String createdBy,
    OffsetDateTime updatedAt,
    String description) {

  public static WebhookSubscriptionResponse from(WebhookSubscription s) {
    return new WebhookSubscriptionResponse(
        s.getId(),
        s.getName(),
        s.getUrl(),
        s.getScopeFilter(),
        s.getDictionaryFilter(),
        s.getEventTypeFilter(),
        maskSecret(s.getHmacSecret()),
        s.isActive(),
        s.getCreatedAt(),
        s.getCreatedBy(),
        s.getUpdatedAt(),
        s.getDescription());
  }

  /** Same payload + plaintext HMAC secret — только для create response. */
  public static WebhookSubscriptionResponse fromWithSecret(WebhookSubscription s, String plaintextSecret) {
    return new WebhookSubscriptionResponse(
        s.getId(),
        s.getName(),
        s.getUrl(),
        s.getScopeFilter(),
        s.getDictionaryFilter(),
        s.getEventTypeFilter(),
        plaintextSecret,
        s.isActive(),
        s.getCreatedAt(),
        s.getCreatedBy(),
        s.getUpdatedAt(),
        s.getDescription());
  }

  private static String maskSecret(String secret) {
    if (secret == null || secret.length() < 8) return "sk_****";
    return "sk_****" + secret.substring(secret.length() - 4);
  }
}
