class TeamInvitation < ApplicationRecord
  STAFF_KINDS = %w[transmission].freeze

  belongs_to :team

  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :token_digest, presence: true, uniqueness: true
  validates :role, inclusion: { in: UserTeam::ROLES }
  validates :staff_kind, inclusion: { in: STAFF_KINDS }

  scope :pending, -> { where(accepted_at: nil).where("expires_at > ?", Time.current) }

  def self.generate_token
    SecureRandom.urlsafe_base64(32)
  end

  def accept!(user)
    ut = UserTeam.find_or_initialize_by(user: user, team: team)
    ut.role = role
    ut.staff_kind = staff_kind
    ut.save!
    update!(accepted_at: Time.current)
  end

  def expired?
    expires_at.past?
  end
end
