class CompetitionTeam < ApplicationRecord

  CODE_CHARS = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z).freeze

  belongs_to :user
  belongs_to :competition

  has_many :team_members, dependent: :destroy
  has_many :users, through: :team_members, source: :user
  has_many :members, -> { without_teachers }, class_name: 'TeamMember'
  has_many :teachers, -> { only_teachers }, class_name: 'TeamMember'

  def group_team_type?
    team_type.zero?
  end

  def personal_team_type?
    team_type == 1
  end

  def en_team_type
    group_team_type? ? 'group' : 'personal'
  end

  def generate_invite_code
    code = CODE_CHARS.sample(6).join
    while self.class.exists?(invite_code: code)
      code = CODE_CHARS.sample(6).join
    end
    self.code = code
    code
  end
end