package cloud.nstart.terravault.ordinis.domain.notification;

import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;

import java.io.Serializable;
import java.util.Objects;

/**
 * Per-user channel opt-in/out (см. migration 0021 + design doc D3).
 *
 * <p>Composite PK {@code (user_id, channel)}. Default {@code enabled=false} для
 * новых rows; bootstrap loadData может включить email для existing reviewer/maker
 * ролей при первом deploy.
 *
 * <p>Channel — lowercase wire format ('email' / 'express' / 'telegram').
 */
@Entity
@Table(name = "user_notification_prefs")
public class UserNotificationPref {

  @Embeddable
  public static class Pk implements Serializable {

    @Column(name = "user_id", length = 128, nullable = false)
    private String userId;

    @Column(name = "channel", length = 16, nullable = false)
    private String channel;

    protected Pk() {}

    public Pk(String userId, String channel) {
      this.userId = userId;
      this.channel = channel;
    }

    public String getUserId() { return userId; }
    public String getChannel() { return channel; }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof Pk pk)) return false;
      return Objects.equals(userId, pk.userId) && Objects.equals(channel, pk.channel);
    }

    @Override
    public int hashCode() {
      return Objects.hash(userId, channel);
    }
  }

  @EmbeddedId
  private Pk id;

  @Column(name = "enabled", nullable = false)
  private boolean enabled;

  protected UserNotificationPref() {}

  public UserNotificationPref(String userId, String channel, boolean enabled) {
    this.id = new Pk(userId, channel);
    this.enabled = enabled;
  }

  public Pk getId() { return id; }
  public String getUserId() { return id.getUserId(); }
  public String getChannel() { return id.getChannel(); }
  public boolean isEnabled() { return enabled; }

  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }
}
