module BeefCake
  class RealmUser < BeefCake::Base
    attributes :id
    associations :realm

    def self.from_uri(uri)
      realm = Realm::TWITCH_LDAP
      id = uri
      if uri.include? ':'
        parts = uri.split(':', 2)
        realm = Realm.find(parts.shift)
        id = parts.shift
      end

      self.from_realm_and_id(realm, id)
    end

    def self.from_realm_and_id(realm, id)
      if realm.id == Realm::TITAN_SUPPORT.id
        return TitanRealmUser.new(id: id)
      elsif realm.id == Realm::TWITCH_LDAP.id
        return TwitchLDAPRealmUser.new(id: id)
      end
      raise "unsupported realm: #{realm}"
    end

    def realm
      raise NotImplementedError
    end

    def uri
      return id if realm == Realm::TWITCH_LDAP
      "#{realm.id}:#{id}"
    end

    def twitch_ldap_user?
      realm.id == Realm::TWITCH_LDAP.id
    end
  end

  class TwitchLDAPRealmUser < RealmUser
    validate :id_exists

    def realm
      Realm::TWITCH_LDAP
    end

    def id_exists
      if Guardian::User.find(id).blank?
        errors.add(:id, "Ldap user #{id} not found")
      end
    end
  end

  class TitanRealmUser < RealmUser
    validate :id_must_be_email

    def realm
      Realm::TITAN_SUPPORT
    end

    def id_must_be_email
      unless /\A([^@\s]+)@[a-z]+\.titan\.xarth\.tv$/i.match?(id)
        errors.add(:id, "Titan Support ID #{id} must be an email with the domain titan.xarth.tv")
      end
    end
  end
end
